Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Class Program in C++

Last Updated on September 22, 2023 by Mayank Dham

In this article, we will write a Class program in C++. We are about to delve into the realm of C++ classes and objects, exploring their definitions and their application in crafting Object-Oriented Programs. Join us as we initiate this journey.

What is Object Oriented Programming?

Before we directly understand what classes and objects are, we first need to understand this object-oriented programming paradigm. So, object-oriented programming is a programming paradigm in which we consider programming entities as objects and we deal with objects and classes using the pillars of object-oriented programming like inheritance, polymorphism, abstraction, and encapsulation.

These 4 pillars of object-oriented programming help us make the code reusable and gives modularity to the code. we can state that object-oriented programming is a style of programming that, by emphasizing real-world elements (called objects), greatly simplifies programming.

We know that C++ has datatypes like int, float, etc. However, when we talk about real-world applications, the data is not that simple. For example, if we have an application for a School, there we don’t have the data in the form of int or string or float, etc. We have the data in the form of real-world entities i.e. students, teachers, classes, etc. For better managing the code and understanding and handling the real-world data, we use Object-Oriented Programming (OOPS).

So, let us now understand what are classes and objects.

What are Objects in OOPS?

We will talk about the formal definition of an object later. For now, we can state that an object is a real-world entity. An object has both properties and behavior. What do we mean by properties and behavior? Consider the following example.

The above-shown image shows a car. It can be considered an object. This is because a car has its properties like its color, brand name, model name, etc., and it also has functions or behaviors like accelerating, decelerating, etc.

A pen is also an example of an object. This is because it has its own properties like color, brand, etc., and has the function of writing.

The formal definition of an object is as follows; “An object is an instance of a class.”

Since we have not yet studied what a class is, we will not be able to understand the formal definition. So, let us first understand the meaning of a Class.

What are Classes in OOPS?

A class is a blueprint of objects. Like we have a blueprint of a building and it tells us the number of rooms and floors in a building but does not tell us exactly what the rooms would look like (i.e. the room interiors), similarly a class defines the properties and behaviors of the objects, however, the values of those properties and the way they behave might vary from object to object.

For instance, a Car is a class. However, a particular car with black color, “Audi” brand name, and “A4” model name can accelerate to a maximum speed of 241 Kmph is an object. This is because there can be another car with a different color, brand, and model name that might only accelerate to 180 Kmph. So, there is a change in the properties (brand name, model name, and color name) and behavior (maximum acceleration).

So, this clears up the formal definition of an Object too i.e. an object is an instance of a class.

Now that we have understood what classes and objects are, let us create a class program in C++.

Class program in C++

The basic syntax for creating a class is shown below.

So, the properties that are kept inside a class (for instance color or brand name in the case of a car or a pen) are called the data members of that class. The functions that we write inside a class (for instance acceleration in the case of a car) are called member functions or member methods or simply, methods.

Access specifiers are required to specify at what levels are the data members and methods accessible outside the class. For instance, a public data member of a class can be accessed from outside the class and a private data member can only be accessed inside the class only. We will study access specifiers in some other articles in detail.

Now let us discuss what we are going to create.

Our Class Program in C++

We will create a Student class. This class, as the name suggests, defines the properties and behaviors of students. To keep it pretty simple, we will have just the name of the student, the roll number, and the marks as the data members and have a setdata() and a printData() method. The class and its object creation are shown below.

Class Program in C++

#include <bits/stdc++.h>
class Student {
  
    public:
    
    string name;
    int roll_no;
    int marks;
    
    void setData(string name,int roll_no, int marks) {
        this->name = name;
        this->roll_no = roll_no;
        this-> marks = marks;
    }
    
    void printData() {
        cout<<"My name is "<<name<<" and my roll number is "<<roll_no<<". I got "<<marks<<" marks out of 100\n";
    }
    
};

int main() {
    // s1 is an object of class Student
    Student s1;
    s1.setData("Guneet",2,95);
    s1.printData();
}

So, we can see that we have created an object of the Student class in the main() function. We have set the name to “Guneet” the roll number is 2 and the marks are 95 using the setData() function by calling it using the dot “.” operator. Then, we called the printData() method using the dot “.” operator.

We have used a keyword called “this” indie the setData() method of the Student class. This is a self-referential pointer. As we see that the names of the parameters of the setData() function and the names of the data members of the class are the same. This is called a namespace collision. The “this” keyword prevents namespace collision as we use “this” with the class data members.

However, preventing namespace collision is not the only function of “this”, the functions of the “this” keyword are not in the scope of this article.

A class can also have some default functions in it called constructors.

Class Program in C++ – Constructors

A function inside the class i.e. a method with the same name as that of the class is called a constructor. Constructors are used in C++ to initialize the objects.

Consider the Program written below.

Class Program in C++ – Program to show Constructor Example

#include <bits/stdc++.h>
class Student {
  
    public:
    
    string name;
    int roll_no;
    int marks;
    
    Student() {
        cout<<"Student Class Constructor called\n";
    }
    
    void setData(string name,int roll_no, int marks) {
        this->name = name;
        this->roll_no = roll_no;
        this-> marks = marks;
    }
    
    void printData() {
        cout<<"My name is "<<name<<" and my roll number is "<<roll_no<<". I got "<<marks<<" marks out of 100\n";
    }
    
};

int main() {
    
    Student s1; //constructor will be called automatically because a new object is created.
    s1.setData("Guneet",2,95);
    s1.printData();
}

As you can see, the constructor is automatically called when an object is created and it does not have any return type also.

A constructor is always placed in the public section of the class. This is because when the object is created and the constructor gets called, it is then that the memory gets allocated to the object. So, if the constructor is made private then memory won’t get allocated, and the object will not be created.

There are 3 types of Constructors in C++. They are as follows.

  1. Default Constructor: This constructor is also known as the zero-argument constructor. This is because no arguments are accepted by the default constructor. We get a default constructor from C++ even if we don’t write our own. The Student() constructor with the print statement shown above is an example of the default constructor. This constructor can be used to initialize the data members for every object, that is, to provide the data members an initial value, since it is called automatically if the parameterized or copy constructor is not invoked.

  2. Parameterized Constructor: As the name suggests, this constructor accepts arguments. This can also be used to initialize the object or remove the setData() function from the classes.

    Class Program in C++ – Parameterized Constructor Example

    #include <bits/stdc++.h>
    class Student {
      
        public:
        
        string name;
        int roll_no;
        int marks;
        
        Student() {
            cout<<"Student Class Constructor called\n";
        }
        
        Student(string name,int roll_no, int marks) {
            this->name = name;
            this->roll_no = roll_no;
            this-> marks = marks;
        }
           
        void printData() {
            cout<<"My name is "<<name<<" and my roll number is "<<roll_no<<". I got "<<marks<<" marks out of 100\n";
        }
        
    };
    
    int main() {
        
        //parameterized constructor is being called
        Student s1("Guneet",2,95);
        s1.printData();
    }

  3. Copy Constructor: This constructor is used to initialize an object using another object of the same class. C++ provides its default copy constructor but it only performs the shallow copy. We need to deep copy the object by creating a Copy constructor of our own. An example of the same is shown below.

    Class Program in C++ – Copy Constructor Example

    #include <bits/stdc++.h>
    class Student {
      
        public:
        
        string name;
        int roll_no;
        int marks;
        
        Student() {
            cout<<"Student Class Constructor called\n";
        }
        
        Student(string name,int roll_no, int marks) {
            this->name = name;
            this->roll_no = roll_no;
            this-> marks = marks;
        }
        
        Student(Student &other) {
            this->name = other.name;
            this->roll_no = other.roll_no;
            this->marks = other.marks;
        }
        
        void setData(string name,int roll_no, int marks) {
            this->name = name;
            this->roll_no = roll_no;
            this-> marks = marks;
        }
        
        void printData() {
            cout<<"My name is "<<name<<" and my roll number is "<<roll_no<<". I got "<<marks<<" marks out of 100\n";
        }
        
    };
    
    int main() {
        
        //parameterized constructor is being called
        Student s1("Guneet",2,95);
        s1.printData();
        
      //copy constructor is being called
        Student s2(s1);
        s2.printData();
    }

So, we have written the class program in C++ and have understood the concepts of Classes, Objects, and constructors. We hope that you liked the discussion and have understood the concepts in detail. We hope to see you again soon at PrepBytes.

Conclusion
Understanding classes and objects is fundamental to harnessing the power of object-oriented programming in C++. By encapsulating data and methods into classes and creating instances of these classes as objects, you can build modular, organized, and efficient programs. Classes provide a blueprint for creating objects with shared characteristics and behaviors, promoting code reusability and maintainability.

Frequently Asked Questions (FAQs) about Class Programs in C++

FAQs related to Class Program in C++ are:

1. How do you declare a class in C++?
You declare a class in C++ using the class keyword, followed by the class name and a block that defines its attributes (data members) and methods (functions).

2. What is the constructor in a class?
A constructor is a special member function in a class that is automatically called when an object is created. It initializes the object’s attributes and can be used to perform setup tasks.

3. What is encapsulation in C++?
Encapsulation is one of the pillars of object-oriented programming. It involves bundling data (attributes) and methods (functions) that operate on the data within a single unit (class), hiding the internal details from outside access.

4. How is inheritance used in C++ classes?
Inheritance allows you to create a new class (derived or child class) that inherits attributes and behaviors from an existing class (base or parent class). This promotes code reuse and allows you to extend the functionality of existing classes.

5. What is polymorphism in C++?
Polymorphism is the ability of different classes to be treated as instances of a common base class. It allows you to write code that can work with objects of different derived classes in a uniform way.

Leave a Reply

Your email address will not be published. Required fields are marked *