Introduction to OOP and constructor

opps_in_cpp


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.

class_and_object

In this example:

  • Car is a class with data members brand and year.
  • The displayInfo function outputs the car’s details.
  • myCar is an object of the Car class, which allows us to set properties and call the displayInfo 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.

access_specifiers

In this example:

  • The balance member is private, making it accessible only within BankAccount.
  • 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 to balance.

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.

constructors

In this example:

  • The constructor initializes width and height 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.

this_pointer

In this example:

  • The this pointer distinguishes between the constructor parameter radius and the member variable radius.

Post a Comment

Your comment will be visible after approval.
© TechTestLog. All rights reserved. Premium By Raushan Design
//My script