×

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On the other hand, Class in a program acts as a blueprint for the object. An object is created for the class, and then we can use the object name to access the class or class member functions. The class generally does not take up any space in the memory.

What is a Class in C++?

Class acts as a blueprint for the object. A class is defined using the keyword class and followed by the name of the class. Following are some keypoints for the class:

  • Statements are written inside the class.
  • The class does not consume any memory.
  • In class, we use public or private keywords to mention the statements' visibility.
  • Members of the class that follow the keyword public have the same access attributes. Private and protected members of a class can also be specified, but those can only be accessed within the particular class.

Syntax of a Class

Defining a class:
class className {
   // some data
   // some functions
};

Example:

class Room {
    public:
        double length;
        double breadth;
        double height;


        double calculateArea(){
            return length * breadth;
        }


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


};

Explanation:

In the above code, we have declared a class with the name Room, with class members as length, breadth, and height of float data type. We have created a class using the class keyword, but it will not work unless an object is created for the class. When we run the code no output will be displayed as the class acts as only a template or blueprint.

C++ Objects

The object is created for the class. Using the object, we run the function members in the class. The class definition provides the blueprint for objects, so objects are created from the classes. Objects of class are declared exactly as variables are.

The syntax for the objects:

className objectVariableName;

Example: Now, let's create an object for the above program

 //class is created using the class keyword.
class Room {
    public:
        double length;
        double breadth;
        double height;


        double calculateArea(){
            return length * breadth;
        }


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


};


void sampleFunction() {
    // create objects for the class 
    Room room1, room2;
}


int main(){
    // create objects for the class
    Room room3, room4;
}

Explanation:

There will be no output for the above code because we have created an object for the class but need to send values to print. In the above code, we have created an object for the class we created in the 1st example. In the two functions, we have created the object for the class room. We have created two objects for the single class.

Now let's send some value to the class using the objects:

#include <iostream>
using namespace std;


//class is created using the class keyword.
class Room {


   public:
    double length;
    double breadth;
    double height;


    double calculateArea() {
        return length * breadth;
    }


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


int main() {


    // create objects for Room class
    Room room1;


    // assign values to data members in the class 
    room1.length = 23.4;
    room1.breadth = 34.6;
    room1.height = 45.6;


    // The area and volutme of the room can be calculated and displayed 
    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;


    return 0;
}

Output:

Classes and Objects in C++

Explanation:

In the above code, we have created a class named Room, which calculates the room size. In the main function, we have created an object for the class. In the main function, we have passed the values in the class. When the values are passed into the class, the class returns the area calculated into the main function using the return statement.

Example:

#include <iostream>
using namespace std;
//class is created using the class keyword.
class Student {
	public:
			int id;
			string name;
};
int main() {
		Student s1; //creating an object of Student class
		s1.id = 305; //assigned the value of id using object
		s1.name = "example.com";; //assigned the value of name using object
		cout<<s1.id<<endl;
		cout<<s1.name<<endl;
		return 0;
} 

Output:

Classes and Objects in C++

Explanation:

In the above example, we have created a class with the name student. In the main class, we created an object for the class, and then, using the object name, we assigned values to the variables.


Related Topics

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.