Jul 8, 2024
Teacher System
class Teacher {
std::string name;
std::string department;
std::string subject;
double salary;
public:
void setSalary(double s) { salary = s; }
double getSalary() { return salary; }
};
Teacher t1;
t1.name = "John";
t1.department = "CS";
t1.subject = "C++";
t1.setSalary(25000);
std::cout << t1.getSalary();
Constructor: Initializes object when created. No return type, same name as class.
Destructor: Deallocates memory when object is destroyed. No arguments, same name with ~
.
class Student {
public:
Student() { std::cout << "Constructor"; }
~Student() { std::cout << "Destructor"; }
};
Student s;
Deriving new classes from existing ones.
Promotes code reusability.
Types: Single, Multi-level, Multiple, Hierarchical, Hybrid.
class Person {
public:
std::string name;
int age;
};
class Student : public Person {
public:
int rollNo;
};
Ability of a function or object to take multiple forms.
Types: Compile-time (Function Overloading, Operator Overloading), Run-time (Virtual Functions).
class Print {
public:
void show(int i) { std::cout << i; }
void show(char c) { std::cout << c; }
};
Print p;
p.show(5); // Prints int
p.show('a'); // Prints char
Hiding unnecessary details and showing essential features.
Implemented using classes and access specifiers.
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() { std::cout << "Drawing Circle"; }
};
Circle c;
c.draw();
Static Variables: Persistent across function calls. Lifetime of the program.
Static Functions: Shared among all objects of the class.
class Example {
public:
static int x;
};
int Example::x = 0;