C++ Classes and Objects
Object-oriented programming with classes
Class Definition
class Person { # define class
public: # public members
string name; # public attribute
int age; # public attribute
void greet() { # public method
cout << "Hello!";
}
};
Constructor and Destructor
class Car {
public:
string brand;
Car(string b) { # constructor
brand = b;
}
~Car() { # destructor
cout << "Object destroyed";
}
};
Access Modifiers
class MyClass {
private: # accessible only within class
int secret;
protected: # accessible in derived classes
int hidden;
public: # accessible everywhere
int visible;
};
Creating Objects
Person p1; # create object
p1.name = "John"; # set attribute
p1.age = 30; # set attribute
p1.greet(); # call method
Car c1("Toyota"); # use constructor
Inheritance
class Animal { # base class
public:
void eat() { }
};
class Dog : public Animal { # derived class
public:
void bark() { }
};