Introduction to Objects in C++

An Object is an instance of a Class. In a class definition, only the conditions for the object is defined; no memory or storage is allocated. To use the data and access the functions defined in the class, we have to create objects. Object is a runtime entity, it is created at runtime.

Syntax:

ClassName ObjectName;

Accessing data members:

The data members of a class are accessed using the dot(‘.’) operator with the object. Accessing a data member depends completely on the access control of that data member.

They can be of 3 types : public, private and protected. The public data members can be accessed in the same way given directly however the private data members are not allowed to be accessed directly by the object.

Example:

// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream>
using namespace std;

// create a class
class Room {

   public:
    double length;
    double breadth;
    double height;

    double calculateArea() {
        return length * breadth;
    }

    double calculateVolume() {
        return length * breadth * height;
    }
};

int main() {

    // create object of Room class
    Room room1;

    // assign values to data members
    room1.length = 42.5;
    room1.breadth = 30.8;
    room1.height = 19.2;

    // compute and show the area and volume of the room
    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;

    return 0;
}

Output:

Area of Room =  1309
Volume of Room =  25132.8

The keyword public is used in the program. This means that the members are public and can be accessed anywhere from the program.

Depending on our needs, we can also create private data members using the private keyword. The private members of a class can only be accessed from within the class.

Returning Object from a Function:

C++ Return Object from Function

Example:

#include <iostream>
using namespace std;

class Student {
   public:
    double m1, m2;
};

// function that returns object of Student
Student createStudent() {
    Student student;

    // Initialize member variables of Student
    student.m1 = 96.5;
    student.m2 = 75.0;

    // print member variables of Student
    cout << "Marks 1 = " << student.m1 << endl;
    cout << "Marks 2 = " << student.m2 << endl;

    return student;
}

int main() {
    Student student1;

    // Call function
    student1 = createStudent();

    return 0;
}

Output

Marks1 = 96.5
Marks2 = 75
We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?