×

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

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 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.