Loading...
C++ Objects and Classes

C++ Objects and Classes

In this tutorial, we will learn about objects and classes and how to use them in C++ with the help of examples.

Objects and Classes

In previous tutorials, we learned about functions and variables. Sometimes it's desirable to put related functions and data in one place so that it's logical and easier to work with.

In object-oriented programming languages like C++, the data and functions (procedures to manipulate the data) are bundled together as a self-contained unit called an object. This programming paradigm is known as object-oriented programming.

A class is an extended concept similar to that of structure in C programming language; this class describes the data properties alone. In C++, a class describes both the properties (data) and behaviors (functions) of objects. Classes are not objects, but they are used to instantiate objects. But before we can create objects and use them in C++, we first need to learn about classes.


C++ Class

A class in C++ is the building block, that leads to Object-Oriented programming. A class is basically a logical entity and mainly a collection of objects.
It is similar to structures in C language. Class can also be defined as user defined data type but it also contains data members and member functions.

  • To access the class members, we use an instance of the class.
  • A C++ class is like a blueprint for an object.
  • It declare & defines what data variables the object will have and what operations can be performed on the class's object.
  • The Class representation of objects and the sets of operations that can be applied to such objects

Create a Class

A class is defined in C++ using keyword class followed by the name of the class. The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.
The Syntax of a Class is:

class className {
   // data
   // functions
};

For example,

class Rect {
public:
    double length;
    double breadth;

    double calculateArea(){   
        return length * breadth;
    }
};

Here, we defined a class named Rect.

The variables length, breadth declared inside the class are known as data members. And, the functions calculateArea() are known as member functions of a class.


C++ Objects

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality.
Object is a runtime entity, it is created at runtime. All the members of the class can be accessed through object. To use the data and access functions defined in the class, we need to create objects.


Syntax to Define Object in C++

className objectVariableName;

The class-name is the name of the class from which an object is to be created. The object-name is the name to be assigned to the new object.
We can create objects of rect class (defined in the above example) as follows:

// sample function
void rectFunct() {
    // create objects
    Rect rect1, rect2;
}
int main(){
    // create objects 
    Rect rect3, rect4;
}

Here, two objects rect1 and rect2 of the Rect class are created in rectFunct(). Similarly, the objects rect3 and rect4 are created in main().

As we can see, we can create objects of a class in any function of the program. We can also create objects of a class within the class itself, or in other classes. Also, we can create as many objects as we want from a single class.


C++ Access Data Members and Member Functions

We can access the data members and member functions of a class by using a . (dot) operator. For example,

rect2.calculateArea();

This will call the calculateArea() function inside the Rect class for object rect2.

Similarly, the data members can be accessed as:

rect1.length = 3.5;

In this case, it initializes the length variable of rect1 to 3.5.


Example 1: C++ Program to use Object and Class

// Program to illustrate the working of objects and class in C++ Programming
#include <iostream>
using namespace std;

// create a class name 'Rect' for rectangle
class Rect {
   public:
    double length;
    double breadth;

    double calculateArea() {
        return length * breadth;
    }
};
int main() {

    // create object of Rect class
    Rect rect1;

    // assign values to data members
    rect1.length = 32.5;
    rect1.breadth = 20.8;

    // calculate and display the area of the rectangle
    cout << "The Area of Rectangle :  " << rect1.calculateArea() << endl;

    return 0;
}

Output

The Area of Rectangle : 676

In this program, we have used the Rect class and its object rect1 to calculate the area of a room. In main(), we assigned the values of length, breadth with the code:

rect1.length = 32.5;
rect1.breadth = 20.8;

We then called the functions calculateArea() to perform the necessary calculations.

Note the use of the keyword public in the program. This means the members are public and can be accessed anywhere from the program.

As per our needs, we can also create private members using the private keyword. The private members of a class can only be accessed from within the class. For example,
 

class Test {

private:

int a;
void function1() { }

public:
    int b;
    void function2() { }
}

Here, a and function1() are private and are. 
Thus they cannot be accessed from outside the class.

On the other hand, b and function2() are accessible from everywhere in the program.

To learn more about public and private keywords, please visit our C++ Class Access Modifiers tutorial.


Example 2: C++ Program to Using public and private

To print the content of a void pointer, we use the static_cast operator. It converts the pointer from void* type to the respective data type of the address the pointer is storing:

// Program to illustrate the working of public and private in C++ Class

#include <iostream>
using namespace std;

class Rect {
   private:
    double length;
    double breadth;

   public:
    // function to initialize private variables
    void getData(double len, double brth) {
        length = len;
        breadth = brth;
    }
    double calculateArea() {
        return length * breadth;
    }
};

int main() {

    // create object of Rect class
    Rect rect1;

    // pass the values of private variables as arguments
    rect1.getData(32.8, 15.0);
    cout << "The Area of Rectangle =  " << rect1.calculateArea() << endl;

    return 0;
}

Output

The Area of Rectangle =  492

The above example is nearly identical to the first example, except that the class variables are now private. Since the variables are now private, we cannot access them directly from main(). Hence, using thefollowing code would be invalid:

// invalid code
obj.length = 32.8;
obj.breadth = 15.0;

Instead, we use the public function getData() to initialize the private variables via the function parameters double len, and double brth.

To learn more on objects and classes, visit these topics:


Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Object & Classes in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Constructors.

- Related Topics