Classes and Objects
In C++, classes are the blueprint for creating objects. A class defines properties (data members) and behaviors (member functions) of an object. An object is an instance of a class, containing its own set of data members.
Example: Basic class with data members and member functions.
In this example:
Car
is a class with data membersbrand
andyear
.- The
displayInfo
function outputs the car’s details. myCar
is an object of theCar
class, which allows us to set properties and call thedisplayInfo
function.
Access Specifiers (public, private, protected)
Access specifiers control the visibility of class members. The three access levels are:
- public: Members are accessible from outside the class.
- private: Members are only accessible from within the class.
- protected: Members are accessible within the class and by derived classes.
Example: Private and public members in a class.
In this example:
- The
balance
member is private, making it accessible only withinBankAccount
. - The
owner
member is public, so it can be accessed and modified from outside the class. getBalance
is a public member function that allows controlled access tobalance
.
Constructors and Destructors
A constructor is a special member function that is automatically called when an object is created. It usually initializes data members. A destructor is called when an object is destroyed, typically for cleanup.
Example: Constructor and destructor in a class.
In this example:
- The constructor initializes
width
andheight
and outputs a message. - The destructor outputs a message when the
rect
object goes out of scope.
The this
Pointer
In C++, this
is a special pointer available in member functions, pointing to the object calling the function. It is often used for clarity or to handle situations where member variables are shadowed by parameters.
Example: Using the this
pointer in a class method.
In this example:
- The
this
pointer distinguishes between the constructor parameterradius
and the member variableradius
.