Category: C++ Class and Objects

https://zain.sweetdishy.com/wp-content/uploads/2026/02/Class-and-Objects-.png

  • Pointer to C++ Classes

    Pointer to Classes

    A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a pointer to a class you use the member access operator -> operator, just as you do with pointers to structures. Also as with all pointers, you must initialize the pointer before using it.

    Example of Pointer to Classes

    Let us try the following example to understand the concept of pointer to a class −

    #include <iostream>usingnamespace std;classBox{public:// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;}doubleVolume(){return length * breadth * height;}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};intmain(void){
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2
       Box *ptrBox;// Declare pointer to a class.// Save the address of first object
       ptrBox =&Box1;// Now try to access a member using member access operator
       cout <<"Volume of Box1: "<< ptrBox->Volume()<< endl;// Save the address of second object
       ptrBox =&Box2;// Now try to access a member using member access operator
       cout <<"Volume of Box2: "<< ptrBox->Volume()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Constructor called.
    Constructor called.
    Volume of Box1: 5.94
    Volume of Box2: 102
  • C++ Friend Functions

    C++ Friend Function

    A friend function of a class is defined outside that class scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

    A friend can be a function, function template, member function, or a class or class template, in which case the entire class and all of its members are friends.

    Declaring Friend Function

    To declare a function as a friend of a class, precede the function prototype in the class definition with the keyword friend as follows

    Syntax

    class Box {
       double width;
       
       public:
          double length;
          friend void printWidth( Box box );
          void setWidth( double wid );
    };
    

    To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne −

    friend class ClassTwo;
    

    Example of Friend Function

    Here is the following code for Function Friend in C++:

    #include <iostream>usingnamespace std;classBox{double width;public:friendvoidprintWidth( Box box );voidsetWidth(double wid );};// Member function definitionvoidBox::setWidth(double wid ){
       width = wid;}// Note: printWidth() is not a member function of any class.voidprintWidth( Box box ){/* Because printWidth() is a friend of Box, it can
       directly access any member of this class */
       cout <<"Width of box : "<< box.width <<endl;}// Main function for the programintmain(){
       Box box;// set box width without member function
       box.setWidth(10.0);// Use friend function to print the wdith.printWidth( box );return0;}

    When the above code is compiled and executed, it produces the following result −

    Width of box : 10
    

    Accessing Private and Protected Members

    The private and protected members of a class are not accessible outside of the class. Still, if you want to access them, you can use the friend function. The friend function provides the ability to directly access the class’s private and protected members.

    Example

    The following example demonstrates accessing private and protected members of a class using the friend function:

    #include <iostream>usingnamespace std;classClassName{private:int privateData;// Private memberprotected:int protectedData;// Protected memberpublic:ClassName():privateData(0),protectedData(0){}// Declare a friend functionfriendvoidfriendFunction(ClassName& obj);};// Friend function definitionvoidfriendFunction(ClassName& obj){
      obj.privateData =42;// Access private member
      obj.protectedData =24;// Access protected member
      cout <<"Private Data: "<< obj.privateData << endl;
      cout <<"Protected Data: "<< obj.protectedData << endl;}intmain(){
      ClassName obj;friendFunction(obj);// Call the friend functionreturn0;}

    When the above code is compiled and executed, it produces the following result −

    Private Data: 42
    Protected Data: 24
    

    Friend Function vs Member Function

    In C++, both friend functions and member functions are used to access and manipulate the data of a class, but still, they have significant differences in their scope and usage.

    Friend Function

    A friend Function is a non-member function that is declared inside a class using the “friend” keyword, it has special access to the class’s private and protected members. Since it’s not a member it is not bound to a specific object, can’t overloaded based on objects, not use this pointer, and cannot be inherited by derived classes. They are defined outside the class but declared inside it.

    Member function

    Whereas the member function is defined within the class and operates using this pointer. It can access all members of the class (private, protected, and public), and as it is tied to class objects, it can be overloaded and inherited by derived classes.

    Friend Classes

    In C++, a friend class is a class that gives access to private and protected members of another class. When a class declares another class as a friend, the second class (the friend) can directly access the private and protected members of the first class.

    This concept is similar to friend functions, but here the friend is an entire class rather than a specific function.

    Syntax

    Here is the following syntax for the friend class in C++:


    class ClassB; // Forward declaration of ClassB class ClassA { private: int dataA; public: // Declare ClassB as a friend of ClassA friend class ClassB; }; Example The following example demonstrates the example of a friend class in C++: #include <iostream> using namespace std; class ClassB; // Forward declaration of ClassB class ClassA { private: int dataA; public: ClassA() : dataA(42) {} // Initialize dataA with a value // Declare ClassB as a friend of ClassA friend class ClassB; }; class ClassB { public: void showDataFromA(const ClassA& objA) { // Access private member of ClassA cout << “Data from ClassA: ” << objA.dataA << endl; } }; int main() { ClassA objA; ClassB objB; // Use ClassB to access ClassA’s private data objB.showDataFromA(objA); return 0; }

  • C++ this Pointer

    this Pointer

    Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter for all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

    Friend functions do not have a this pointer because friends are not members of a class. Only member functions have this pointer.

    Example of this Pointer

    Let us try the following example to understand the concept of this pointer −

    #include <iostream>usingnamespace std;classBox{public:// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;}doubleVolume(){return length * breadth * height;}intcompare(Box box){returnthis->Volume()> box.Volume();}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};intmain(void){
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2if(Box1.compare(Box2)){
          cout <<"Box2 is smaller than Box1"<<endl;}else{
          cout <<"Box2 is equal to or larger than Box1"<<endl;}return0;}

    When the above code is compiled and executed, it produces the following result −

    Constructor called.
    Constructor called.
    Box2 is equal to or larger than Box1
    

    Return Calling Object’s Reference Using this Pointer

    To implement chain function calls, you need the reference of a calling object. You can use the “this” pointer to return the reference of the calling object.

    Syntax

    Here is the syntax:

    Test&Test::func(){return*this;}

    Example

    The following example demonstrates how you can return the reference to the calling object:

    #include <iostream>usingnamespace std;classCoordinates{private:int latitude;int longitude;public:Coordinates(int lat =0,int lon =0){this->latitude = lat;this->longitude = lon;}
    
      Coordinates&setLatitude(int lat){
        latitude = lat;return*this;}
    
      Coordinates&setLongitude(int lon){
        longitude = lon;return*this;}voiddisplay()const{
        cout <<"Latitude = "<< latitude <<", Longitude = "<< longitude << endl;}};intmain(){
      Coordinates location(15,30);// Chained function calls modifying the same object
      location.setLatitude(40).setLongitude(70);
    
      location.display();return0;}

    When the above code is compiled and executed, it produces the following result −

    Latitude = 40, Longitude = 70
    

    Characteristics of the “this” Pointer

    • The “this” pointer refers to the current instance of the object, where it allows the member function to access the object’s attributes and methods.
    • The “this” pointer is implicitly passed to all non-static member functions, where you don’t need to explicitly write this in code.
    • this points to the memory location of the current object.
    • If there is a name conflict between a parameter and a member variable, this can be used to differentiate the member variable from the local parameter.
    • the “this” pointer is constant (const), meaning it cannot be modified.
    • Since this is a pointer, it can be dereferenced to access the current object.

    this Pointer in Const Member Functions Vs Static Member Functions

    In const member functions, this pointer is a pointer to a constant object (const MyClass*), where the object’s members cannot be modified within the function, resulting in an object remaining unchanged when calling const functions.

    Whereas static member functions don’t have this pointer because they are not associated with any specific instance of the class, they belong to the class itself and can only access static members or methods, as they do not operate on object-specific data.

    Example

    Here is the given example representing both with this pointer in the Const member function Vs static member function.

    #include <iostream>classMyClass{public:MyClass(int val):data(val){}// Const member function (has 'this' pointer, but it's a const pointer)voidprintData()const{
             std::cout <<"Data: "<< data << std::endl;// 'this' points to a const object// Uncommenting the next line will cause an error because 'this' is const// data = 10;  // Error: cannot modify 'data' in a const member function}// Static member function (no 'this' pointer, operates on class-level data)staticvoidshowMessage(){
             std::cout <<"This is a static function!"<< std::endl;// Uncommenting the next line will cause an error because static functions can't access instance members// std::cout << "Data: " << data << std::endl;  // Error: 'data' is not accessible}private:int data;};intmain(){
       MyClass obj(5);// Calling const member function (can access 'this' as const)
       obj.printData();// Calling static member function (no 'this' pointer available)MyClass::showMessage();return0;}

    Output

    Data: 5
    This is a static function!
    

    Common Use Cases of this Pointer

    In C++, this pointer is a special pointer, which refers to the current instances of a class in non-static member functions.

    Here we will see its common use cases in the following.

    • this pointer helps in preventing self-assignment in assignment operators making sure that an object doesn’t assign itself to itself.
    • this pointer makes method chaining possible by returning the current object (usually through *this), allowing you to call several methods on the same object in a single line of code.
    • It allows for direct access to the object’s members within member functions.
    • It is important in copy constructors and assignment operators, as it helps return the current object during assignments.
    • it is also useful in Polymorphism, Inherited Classes, and Implement Fluent Interfaces, allowing smooth method chaining.

    Limitations of this Pointer

    The “this” pointer is a powerful feature in C++, but it has certain limitations and potential pitfalls that developers should keep in mind to prevent errors or unexpected behavior.

    • this pointer isn’t available in static member functions because static functions are tied to the class itself, not to any specific object.
    • It can help differentiate between member variables and local variables when their names overlap. However, if a local variable shadows a member variable, it can still lead to confusion or ambiguity.
    • this pointer always refers to the current object, but using it after the object is destroyed or while it’s being destroyed can cause undefined behavior.
    • When dealing with multiple inheritance, conflicts can occur if different base classes share members with identical names. This can make it unclear which member the this pointer is pointing to, leading to ambiguity.
    • Returning *this from a temporary object can be risky since it might leave behind a dangling reference, which could cause unexpected or undefined behavior.
  • C++ Inline Functions

    What is an Inline Function in C++

    C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

    Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.

    Defining an Inline Function

    To define an inline function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.

    A function definition in a class definition is an inline function definition, even without the use of the inline specifier.

    Example

    Following is an example, which makes use of inline function to return max of two numbers −

    #include <iostream>usingnamespace std;inlineintMax(int x,int y){return(x > y)? x : y;}// Main function for the programintmain(){
       cout <<"Max (20,10): "<<Max(20,10)<< endl;
       cout <<"Max (0,200): "<<Max(0,200)<< endl;
       cout <<"Max (100,1010): "<<Max(100,1010)<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Max (20,10): 20
    Max (0,200): 200
    Max (100,1010): 1010
    

    Inline Function with Classes

    By default, all the functions that are defined inside a class are implicitly inline. If you want to explicitly define a function as inline, then you have to declare a function inside the class and write its definition outside the class. The inline keyword is used with the function definition that is outside of the class declaration.

    Example

    In the following example, we are defining an inline function with the class −

    #include <iostream>usingnamespace std;classNumber{private:int num1;int num2;public:// Function to set the valuesvoidsetValues(int a,int b);// Function to print the valuesvoidprintValues();// Inline function to add the two numbersinlineintaddNumbers();};// Member function definitionsvoidNumber::setValues(int a,int b){
        num1 = a;
        num2 = b;}voidNumber::printValues(){
        cout <<"Number 1: "<< num1 <<", Number 2: "<< num2 << endl;}// Inline function definitioninlineintNumber::addNumbers(){return num1 + num2;}intmain(){// Create an object
        Number n;// Set the values
        n.setValues(10,20);// Print the values
        n.printValues();// Add the numbers and print the resultint sum = n.addNumbers();
        cout <<"Sum of the numbers: "<< sum << endl;return0;}

    Advantages of Inline Function

    The following are the advantages of using inline function −

    • In the case of an inline function, the function call overhead does not occur.
    • The inline function saves the overhead of the push and pop variables on the stack, when the function is called.
    • An inline function saves the overhead of a return call from a function.
    • When an inline function is created, the compiler may perform context specific optimization on the body of the function. This kind of optimization is not performed for normal functions.
    • Using small inline functions may be useful for embedded systems, because inline can yield less code than the function call preamble and return.

    Disadvantages of Inline Function

    Some of the disadvantages of inline functions are as follows –

    • When we use an inline function, the size of the code is increased because the compiler replaces each function call with the inline function code.
    • Large sized code takes more memory and time to compiler the code.
    • The compilation process slows down because the compiler evaluates and replaces the function code at the place function calls.
    • In some of the cases, the program’s performance may slow down.
    • Based on the function code complexity, the compiler may ignore the inline keyword. Thus, the application of the inline function is limited.

    Some of the disadvantages of inline function are as follows −

  • C++ – Static Member Function

    Static Member Function

    Static Member Function in C++ is a special kind of function that belongs to the class itself rather than any specific object. A static keyword is used to define those functions. They can be directly called by using just the class name, without creating an instance of the class, which is an object.

    These are only accessible within the body of the class they are defined in, thus, implementing class-wide operations and certain security measures.

    Syntax

    Here is the given syntax for static member functions in C++:

    classClassName{public:static returnType functionName(parameters){// Function body}};

    Example of Static Member Function

    Here is the following example for the static member function:

    #include <iostream>usingnamespace std;classMyClass{public:staticvoiddisplayMessage(){
             cout <<"Hello, World!";}};intmain(){// Calling static member functionMyClass::displayMessage();return0;}

    Output

    Hello, World!
    

    Explanation

    • We define a class MyClass with a public static member function displayMessage().
    • The function simply prints “Hello, World!”.
    • In the main function, we directly call the function using the class name. Observe we haven’t created an instance of the class to call the function.

    Key features of Static Member Functions

    • There’s no access to this pointer with static functions as they’re not tied to an object instance.
    • These functions can be invoked using a class name.
    • They can only work with static members or other static functions of the class.

    When should static member functions be used?

    These are best suited for tasks that involve shared data and logic which is unrelated to specific objects. Here are some scenarios −

    • Maintaining counters, and handling global configurations.
    • In implementing interface methods that don’t require an object state.
    • Utility or helper functions like mathematical operations, data validations, etc.

    Example

    #include <iostream>usingnamespace std;classMathOperation{public:staticintsquare(int num){return num * num;}};intmain(){
       std::cout <<"Square of 2: "<<MathOperation::square(2)<<'\n';return0;}

    Output

    Square of 2: 4
  • Static Data Members in C++

    Static Data Members in C++

    In C++, a static data member is a class member or class-level variable, which is shared by all instances(objects) of that class. This is not like regular data members, which have separate copies for each object of the class, a static data member has only one copy for the entire class, which can be shared across all instances, which means that all objects of the class can access and modify the same value.

    Static Data Member Declaration

    This is the following syntax for declaring a static data member inside the class using a static keyword.

    classClassName{public:static dataType staticMemberName;};

    Static Data Member Initialization

    This is the following syntax for defining and initializing a static data member outside the class, which is done using ClassName:: scope resolution operator.

    dataType ClassName::staticMemberName = initialValue;

    Accessing Static Data Members

    Static data members can be accessed in two ways, that is −

    • Using the Class Name (Recommended)
    • Using an Object (Not Recommended)

    Here we will see the following differences between them and their syntax and examples.

    Accessing Static Data Members Using the Class Name

    This is the very common and preferred way of accessing a static data member, which is done by using the scope resolution operator ::

    Syntax

    Here is the following syntax for it.

    ClassName::staticDataMember;

    Accessing Static Data Members Using an Object

    You can also access a static data member using an object, but it’s generally not recommended because static members are independent of any specific object, and using an object can mislead it.

    Syntax

    Here is the following syntax for it.

    objectName.staticDataMember;

    Example

    Here is the following example of a static data member in C++.

    #include <iostream>#include <string>usingnamespace std;classBook{private:
          string title;// Title of the book
          string author;// Author of the bookpublic:// Static data member to track total books in the librarystaticint totalBooks;// Constructor to initialize the book's title and authorBook(string bookTitle, string bookAuthor){
          title = bookTitle;
          author = bookAuthor;
          totalBooks++;// Increment totalBooks every time a new book is created}// Static method to display the total number of booksstaticvoiddisplayTotalBooks(){
          cout <<"Total number of books in the library: "<< totalBooks << endl;}// Method to display information about the bookvoiddisplayBookInfo(){
          cout <<"Book Title: "<< title <<", Author: "<< author << endl;}};// Initialize the static data member outside the classint Book::totalBooks =0;intmain(){// Creating book objects (books being added to the library)
       Book book1("The Catcher in the Rye","J.D. Salinger");
       Book book2("To Kill a Mockingbird","Harper Lee");
       Book book3("1984","George Orwell");// Displaying the total number of books using the static methodBook::displayTotalBooks();// Displaying the details of each book
       book1.displayBookInfo();
       book2.displayBookInfo();
       book3.displayBookInfo();// Adding more books to the library
       Book book4("Pride and Prejudice","Jane Austen");
       Book book5("The Great Gatsby","F. Scott Fitzgerald");// Displaying the updated total number of booksBook::displayTotalBooks();return0;}

    Output

    Total number of books in the library: 3
    Book Title: The Catcher in the Rye, Author: J.D. Salinger
    Book Title: To Kill a Mockingbird, Author: Harper Lee
    Book Title: 1984, Author: George Orwell
    Total number of books in the library: 5
    

    Use Case of Static Data Members

    Static data members in C++ are the names given to those variables that can be accessed by all instances of a class. That is, they are not tied to any object. Let’s see some common use cases for it.

    1. Tracking object creation

    A very common usage of static data members is to track the number of instances or objects for a class.

    2. Maintaining global configurations or settings

    These are used to create global settings or configuration components that need to be accessed by all instances of a class in any context.

    3. Cache or Shared Resource Management

    Static data members are also useful for managing shared resources or caching in a system, where it’s possible for multiple objects to access the same resource.

    4. Implementing design patterns like Singleton

    The implementation of design patterns, such as Singleton, is also advantageous, as this particular pattern often uses static data members to ensure that there exists only one instance of a class throughout the entire program. The static member holds the exclusive instance of the class.

    5. Tracking global counters or actions across objects

    It also helps in tracking a global count of a particular object or action, like counting the number of logins, transactions, or events.

  • Static Members of a C++ Class

    Static Members of a Class

    We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

    A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can’t put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

    Example

    Let us try the following example to understand the concept of static data members −

    #include <iostream>usingnamespace std;classBox{public:staticint objectCount;// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;// Increase every time object is created
             objectCount++;}doubleVolume(){return length * breadth * height;}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};// Initialize static member of class Boxint Box::objectCount =0;intmain(void){
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2// Print total number of objects.
       cout <<"Total objects: "<< Box::objectCount << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Constructor called.
    Constructor called.
    Total objects: 2
    

    Static Function Members

    By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

    A static member function can only access static data member, other static member functions and any other functions from outside the class.

    Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

    Example

    Let us try the following example to understand the concept of static function members −

    #include <iostream>usingnamespace std;classBox{public:staticint objectCount;// Constructor definitionBox(double l =2.0,double b =2.0,double h =2.0){
             cout <<"Constructor called."<< endl;
             length = l;
             breadth = b;
             height = h;// Increase every time object is created
             objectCount++;}doubleVolume(){return length * breadth * height;}staticintgetCount(){return objectCount;}private:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};// Initialize static member of class Boxint Box::objectCount =0;intmain(void){// Print total number of objects before creating object.
       cout <<"Inital Stage Count: "<<Box::getCount()<< endl;
    
       Box Box1(3.3,1.2,1.5);// Declare box1
       Box Box2(8.5,6.0,2.0);// Declare box2// Print total number of objects after creating object.
       cout <<"Final Stage Count: "<<Box::getCount()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Inital Stage Count: 0
    Constructor called.
    Constructor called.
    Final Stage Count: 2
    

    Use Cases for Static Members

    Here are the following use cases:

    • A singleton pattern is a design pattern that makes sure that a class has only one instance and provides a global point of access to it. Here static members are perfect for implementing this pattern because they allow to maintenance of a single shared instance of the class.
    • Static members are often used to manage shared resources or counters that should be shared across all instances of a class.
    • Static members can be used to store global configuration settings or constants, useful for managing a pool of resources (e.g., a cache, database connection pool, etc.) and implementing a logging system that is shared across instances. which is shared across all instances of a class.
    • Static members can be used for Tracking Method calls.
  • C++ Class Access Modifiers

    C++ access modifiers are used for data hiding implementation. Data hiding is one of the important features of object-oriented programming, which allows the functions of a program to access directly the internal representation of a class type.The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.

    A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.

    classBase{public:// public members go hereprotected:// protected members go hereprivate:// private members go here};

    Public Access Modifier

    The public access modifier defines public data members and member functions that are accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function.

    Example

    The following example demonstrates the use of public access modifier −

    #include <iostream>usingnamespace std;classLine{public:double length;voidsetLength(double len );doublegetLength(void);};// Member functions definitionsdoubleLine::getLength(void){return length ;}voidLine::setLength(double len){
       length = len;}// Main function for the programintmain(){
       Line line;// set line length
       line.setLength(6.0); 
       cout <<"Length of line : "<< line.getLength()<<endl;// set line length without member function
       line.length =10.0;// OK: because length is public
       cout <<"Length of line : "<< line.length <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Length of line : 6
    Length of line : 10
    

    Private Access Modifier

    The private access modifier defines private data members and member functions that cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

    By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member.

    Example

    The following example demonstrates the use of private access modifier −

    classBox{double width;public:double length;voidsetWidth(double wid );doublegetWidth(void);};

    Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.

    #include <iostream>usingnamespace std;classBox{public:double length;voidsetWidth(double wid );doublegetWidth(void);private:double width;};// Member functions definitionsdoubleBox::getWidth(void){return width ;}voidBox::setWidth(double wid ){
       width = wid;}// Main function for the programintmain(){
       Box box;// set box length without member function
       box.length =10.0;// OK: because length is public
       cout <<"Length of box : "<< box.length <<endl;// set box width without member function// box.width = 10.0; // Error: because width is private
       box.setWidth(10.0);// Use member function to set it.
       cout <<"Width of box : "<< box.getWidth()<<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Length of box : 10
    Width of box : 10
    

    Protected Access Modifier

    The protected access modifier defines protected data members and member functions that are very similar to a private member, but it provides one additional benefit that they can be accessed in child classes, which are called derived classes.

    You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box.

    Example

    Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox.

    #include <iostream>usingnamespace std;classBox{protected:double width;};classSmallBox:Box{// SmallBox is the derived class.public:voidsetSmallWidth(double wid );doublegetSmallWidth(void);};// Member functions of child classdoubleSmallBox::getSmallWidth(void){return width ;}voidSmallBox::setSmallWidth(double wid ){
       width = wid;}// Main function for the programintmain(){
       SmallBox box;// set box width using member function
       box.setSmallWidth(5.0);
       cout <<"Width of box : "<< box.getSmallWidth()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Width of box : 5
  • C++ Class Member Functions

    A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

    Let us take previously defined class to access the members of the class using a member function instead of directly accessing them −

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a boxdoublegetVolume(void);// Returns box volume};

    Defining Class Member Functions

    Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below −

    Defining Member Function inside the Class

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a boxdoublegetVolume(void){return length * breadth * height;}};

    Defining Member Function outside of the Class

    If you like, you can define the same function outside the class using the scope resolution operator (::) as follows −

    doubleBox::getVolume(void){return length * breadth * height;}

    Here, only important point is that you would have to use class name just before :: operator.

    Calling (Accessing) Member Functions

    A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows −

    Box myBox;// Create an object
    
    myBox.getVolume();// Call member function for the object

    Example

    Let us put above concepts to set and get the value of different class members in a class −

    #include <iostream>usingnamespace std;classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box// Member functions declarationdoublegetVolume(void);voidsetLength(double len );voidsetBreadth(double bre );voidsetHeight(double hei );};// Member functions definitionsdoubleBox::getVolume(void){return length * breadth * height;}voidBox::setLength(double len ){
       length = len;}voidBox::setBreadth(double bre ){
       breadth = bre;}voidBox::setHeight(double hei ){
       height = hei;}// Main function for the programintmain(){
       Box Box1;// Declare Box1 of type Box
       Box Box2;// Declare Box2 of type Boxdouble volume =0.0;// Store the volume of a box here// box 1 specification
       Box1.setLength(6.0); 
       Box1.setBreadth(7.0); 
       Box1.setHeight(5.0);// box 2 specification
       Box2.setLength(12.0); 
       Box2.setBreadth(13.0); 
       Box2.setHeight(10.0);// volume of box 1
       volume = Box1.getVolume();
       cout <<"Volume of Box1 : "<< volume <<endl;// volume of box 2
       volume = Box2.getVolume();
       cout <<"Volume of Box2 : "<< volume <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Volume of Box1 : 210
    Volume of Box2 : 1560
  • C++ Classes and Objects

    The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.

    A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

    C++ Class Definitions

    When you define a class, you define a blueprint for a data type. This doesn’t actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

    A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −

    classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};

    The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

    Define C++ Objects

    A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −

    Box Box1;// Declare Box1 of type Box
    Box Box2;// Declare Box2 of type Box

    Both of the objects Box1 and Box2 will have their own copy of data members.

    Accessing the Data Members

    The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear −

    #include <iostream>usingnamespace std;classBox{public:double length;// Length of a boxdouble breadth;// Breadth of a boxdouble height;// Height of a box};intmain(){
       Box Box1;// Declare Box1 of type Box
       Box Box2;// Declare Box2 of type Boxdouble volume =0.0;// Store the volume of a box here// box 1 specification
       Box1.height =5.0; 
       Box1.length =6.0; 
       Box1.breadth =7.0;// box 2 specification
       Box2.height =10.0;
       Box2.length =12.0;
       Box2.breadth =13.0;// volume of box 1
       volume = Box1.height * Box1.length * Box1.breadth;
       cout <<"Volume of Box1 : "<< volume <<endl;// volume of box 2
       volume = Box2.height * Box2.length * Box2.breadth;
       cout <<"Volume of Box2 : "<< volume <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Volume of Box1 : 210
    Volume of Box2 : 1560
    

    It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

    Classes and Objects in Detail

    So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below −

    Sr.NoConcept & Description
    1Class Member FunctionsA member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
    2Class Access ModifiersA class member can be defined as public, private or protected. By default members would be assumed as private.
    3Constructor & DestructorA class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
    4Copy ConstructorThe copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
    5Friend Functionsfriend function is permitted full access to private and protected members of a class.
    6Inline FunctionsWith an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
    7this PointerEvery object has a special pointer this which points to the object itself.
    8Pointer to C++ ClassesA pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
    9Static Members of a ClassBoth data members and function members of a class can be declared as static.