Open In App

C++ Classes and Objects

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.

What is a Class in C++?

A class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels, speed limits, and mileage are their properties.

  • A Class is a user-defined data type that has data members and member functions.
  • Data members are the data variables and member functions are the functions used to manipulate these variables together, these data members and member functions define the properties and behaviour of the objects in a Class.
  • In the above example of class Car, the data member will be speed limit, mileage, etc, and member functions can be applying brakes, increasing speed, etc.

But we cannot use the class as it is. We first have to create an object of the class to use its features. An Object is an instance of a Class.

Note: When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

To master classes and objects and their practical use, check out our Complete C++ Course, where you’ll learn how to design and implement object-oriented solutions.

Defining Class in C++

A class is defined in C++ using the keyword class followed by the name of the class. The following is the syntax:

class ClassName {
access_specifier:
// Body of the class
};

Here, the access specifier defines the level of access to the class’s data members.

Example

class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};

C++ Class and Object

If you want to dive deep into STL and understand its full potential, our Complete C++ Course offers a complete guide to mastering containers, iterators, and algorithms provided by STL.

What is an Object in C++?

When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax to Create an Object

We can create an object of the given class in the same way we declare the variables of any other inbuilt data type.

ClassName ObjectName;

Example

MyClass obj;

In the above statement, the object of MyClass with name obj is created.

Accessing Data Members and Member Functions

The data members and member functions of the class can be accessed using the dot(‘.’) operator with the object. For example, if the name of the object is obj and you want to access the member function with the name printName() then you will have to write:

obj.printName()

Example of Class and Object in C++

The below program shows how to define a simple class and how to create an object of it.

C++
// C++ program to illustrate how create a simple class and
// object
#include <iostream>
#include <string>

using namespace std;

// Define a class named 'Person'
class Person {
public:
    // Data members
    string name;
    int age;

    // Member function to introduce the person
    void introduce()
    {
        cout << "Hi, my name is " << name << " and I am "
             << age << " years old." << endl;
    }
};

int main()
{
    // Create an object of the Person class
    Person person1;

    // accessing data members
    person1.name = "Alice";
    person1.age = 30;

    // Call the introduce member method
    person1.introduce();

    return 0;
}

Output
Hi, my name is Alice and I am 30 years old.

Access Modifiers

In C++ classes, we can control the access to the members of the class using Access Specifiers. Also known as access modifier, they are the keywords that are specified in the class and all the members of the class under that access specifier will have particular access level.

In C++, there are 3 access specifiers that are as follows:

  1. Public: Members declared as public can be accessed from outside the class.
  2. Private: Members declared as private can only be accessed within the class itself.
  3. Protected: Members declared as protected can be accessed within the class and by derived classes.

If we do not specify the access specifier, the private specifier is applied to every member by default.

Example of Access Specifiers

C++
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks {
private:
    string geekname;
    // Access specifier
public:
    // Member Functions()
    void setName(string name) { geekname = name; }

    void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
    // Declare an object of class geeks
    Geeks obj1;
    // accessing data member
    // cannot do it like: obj1.geekname = "Abhi";
    obj1.setName("Abhi");
    // accessing member function
    obj1.printname();
    return 0;
}

Output
Geekname is:Abhi

In the above example, we cannot access the data member geekname outside the class. If we try to access it in the main function using dot operator, obj1.geekname, then program will throw an error.

Member Function in C++ Classes

There are 2 ways to define a member function:

  • Inside class definition
  • Outside class definition

Till now, we have defined the member function inside the class, but we can also define the member function outside the class. To define a member function outside the class definition,

  • We have to first declare the function prototype in the class definition.
  • Then we have to use the scope resolution:: operator along with the class name and function name.

Example

C++
// C++ program to demonstrate member function
// definition outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
    string geekname;
    int id;

    // printname is not defined inside class definition
    void printname();

    // printid is defined inside class definition
    void printid() { cout << "Geek id is: " << id; }
};

// Definition of printname using scope resolution operator
// ::
void Geeks::printname()
{
    cout << "Geekname is: " << geekname;
}
int main()
{

    Geeks obj1;
    obj1.geekname = "xyz";
    obj1.id = 15;

    // call printname()
    obj1.printname();
    cout << endl;

    // call printid()
    obj1.printid();
    return 0;
}

Output
Geekname is: xyz
Geek id is: 15
 

Note that all the member functions defined inside the class definition are by default inline, but you can also make any non-class function inline by using the keyword inline with them. Inline functions are actual functions, which are copied everywhere during compilation, like pre-processor macro, so the overhead of function calls is reduced. 

Note: Declaring a friend function is a way to give private access to a non-member function.

Constructors

Constructors are special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition.

There are 4 types of constructors in C++ classes:

  • Default Constructors: The constructor that takes no argument is called default constructor.
  • Parameterized Constructors: This type of constructor takes the arguments to initialize the data members.
  • Copy Constructors: Copy constructor creates the object from an already existing object by copying it.
  • Move Constructor: The move constructor also creates the object from an already existing object but by moving it.

Example of Constructor

C++
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
    public:
    int id;
    
    //Default Constructor
    Geeks()
    {
        cout << "Default Constructor called" << endl; 
        id=-1;
    }
    
    //Parameterized Constructor
    Geeks(int x)
    {
        cout <<"Parameterized Constructor called "<< endl;
        id=x;
    }
};
int main() {
    
    // obj1 will call Default Constructor
    Geeks obj1;
    cout <<"Geek id is: "<<obj1.id << endl;
    
    // obj2 will call Parameterized Constructor
    Geeks obj2(21);
    cout <<"Geek id is: " <<obj2.id << endl;
    return 0;
}

Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called 
Geek id is: 21

Note: If the programmer does not define the constructor, the compiler automatically creates the default, copy and move constructor.

Destructors

Destructor is another special member function that is called by the compiler when the scope of the object ends. It deallocates all the memory previously used by the object of the class so that there will be no memory leaks. The destructor also have the same name as the class but with tilde(~) as prefix.

Example of Destructor

C++
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
    public:
    int id;
    
    //Definition for Destructor
    ~Geeks()
    {
        cout << "Destructor called for id: " << id <<endl; 
    }
};

int main() 
  {
    Geeks obj1;
    obj1.id=7;
    int i = 0;
    while ( i < 5 )
    {
        Geeks obj2;
        obj2.id=i;
        i++;        
    } // Scope for obj2 ends here

    return 0;
  } // Scope for obj1 ends here

Output
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7

Interesting Fact (Rare Known Concept)

Why do we give semicolons at the end of class?

Many people might say that it’s a basic syntax and we should give a semicolon at the end of the class as its rule defines in cpp. But the main reason why semi-colons are there at the end of the class is compiler checks if the user is trying to create an instance of the class at the end of it. 

Yes just like structure and union, we can also create the instance of a class at the end just before the semicolon. As a result, once execution reaches at that line, it creates a class and allocates memory to your instance.

C++
#include <iostream>
using namespace std;

class Demo{
   int a, b;
    public:
    Demo()   // default constructor
    {
        cout << "Default Constructor" << endl;
    }
    Demo(int a, int b):a(a),b(b)  //parameterised constructor
    {
        cout << "parameterized constructor -values" << a  << " "<< b << endl;
    }
    
}instance;


int main() {
   
    return 0;
}

Output
Default Constructor

We can see that we have created a class instance of Demo with the name “instance”, as a result, the output we can see is Default Constructor is called.

Similarly, we can also call the parameterized constructor just by passing values here      

C++
#include <iostream>
using namespace std;

class Demo{
    public:
    int a, b;
    Demo()
    {
        cout << "Default Constructor" << endl;
    }
    Demo(int a, int b):a(a),b(b)
    {
        cout << "parameterized Constructor values-" << a << " "<< b << endl;
    }
     
    
    
}instance(100,200);


int main() {
   
    return 0;
}

Output
parameterized Constructor values-100 200

So by creating an instance just before the semicolon, we can create the Instance of class.



Previous Article
Next Article

Similar Reads

Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Local Classes in C++
A class declared inside a function becomes local to that function and is called Local Class in C++. A local class name can only be used locally i.e., inside the function and not outside it.The methods of a local class must be defined inside it only.A local class can have static functions but, not static data members. For example, in the following p
6 min read
Anonymous classes in C++
Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions. Examples to illustrate Anonymous Classes Creating single object of Anonymous Class : In
3 min read
C++ Stream Classes Structure
In C++ there are number of stream classes for defining various streams related with files and for doing input-output operations. All these classes are defined in the file iostream.h. Figure given below shows the hierarchy of these classes. ios class is topmost class in the stream classes hierarchy. It is the base class for istream, ostream, and str
4 min read
Expression Trees Using Classes in C++ with Implementation
Prerequisite: Expression Tree The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be: In expression trees, leaf nodes are operands and non-leaf nodes are operators. That means an expression tree is a binary t
4 min read
Self-Referential Classes in C++
A class is a building block in C++ that leads to Object-Oriented programming. It is a user-defined type that holds its own data members and member functions. These can be accessed by creating an instance of the type class. Self-referential classes are a special type of classes created specifically for a Linked List and tree-based implementation in
3 min read
Nested Classes in C++
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed. For example, program 1 compiles without any error and program 2
1 min read
Trivial classes in C++
When a class or struct in C++ has compiler-provided or explicitly defaulted special member functions, then it is a trivial type. It occupies a contiguous memory area. It can have members with different access specifiers. Trivial types have a trivial default constructor, trivial copy constructor, trivial copy assignment operator and trivial destruct
1 min read
What Requirements Must std::map Key Classes Meet to be Valid Keys?
In C++, std::map is a commonly used associative container that stores elements in key-value pairs, allowing for efficient data retrieval based on keys. One common question that arises is what requirements must be met for a class to be used as a key in std::map. In this article, we will learn the requirements for key classes in std::map, understand
3 min read
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specify the storage class for a variable. SyntaxTo speci
8 min read
File Handling through C++ Classes
File handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk).How to achieve the File HandlingFor achieving file handling we need to follow the following steps:- STEP 1-Naming a file STEP 2-Opening a file STEP 3-Writing data into the file STEP 4-Reading data from the file ST
8 min read
Introduction to Complex Objects and Composition
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation
4 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors:
6 min read
Anonymous Objects in C++
Prerequisite: Class and Objects in C++ An Object is an instance of a Class. A class has no memory allocated it is just like a blueprint, but when it is instantiated (i.e. an object is created) memory is allocated just like the real-world instance of that blueprint. An object that does not have a reference variable is known as an anonymous object. T
4 min read
Creating a Vector of Class Objects in C++
Prerequisites: Object Oriented Programming in C++Vector in C++ Class is a user-defined data type that can be accessed by creating objects or instances of that class. A vector is a type of container which can store elements of a similar type. Vector of Class The vector of class objects is an example of a custom vector made where we can store multipl
3 min read
Reference to Dynamic Objects in C++
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically. The dynamic objects can be created with the
3 min read
How to Parse an Array of Objects in C++ Using RapidJson?
RapidJSON is an open-source C++ library for parsing and serializing JSON (JavaScript Object Notation) data. It is designed to be fast and efficient, with a focus on simplicity and ease of use. It is widely used in a variety of applications and is known for its fast performance and low memory overhead. It is a popular choice for parsing and serializ
4 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
How to Restrict Dynamic Allocation of Objects in C++?
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scop
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
Array of Objects in C++ with Examples
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in
5 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Practice Tags :
three90RightbarBannerImg