Site icon DataFlair

C++ Class and Object – A tutorial to reign the C++ Programming

Free C++ course with real-time projects Start Now!!

One of the striking features of C++ that makes it uniquely different from C, which is the implementation of class and object. We already know that the implementation of classes is a core concept of object-oriented programming and hence classes are of utmost importance hence dealing with real-time problems. Bjarne Stroustrup, the father of C++ informally refers to C++ as “C with classes”. This phrase clearly connotes the immense importance of classes and objects in C++.

In this tutorial, we will discuss:

After completing this tutorial, you yourself would learn how to use classes to implement data abstraction, encapsulation, polymorphism, and data hiding.

1. C++ Class

Just like a structure in C gives us a way to group data elements, classes in C++ place the data elements as well as member functions as a single entity.

A class is nothing but a way to represent a group of logically related data members and member functions. They may or may not be of similar data types. With the addition to data types, classes give you the provision to keep your data secure and add functions within the class, unlike what we saw in structures in C.

2. Real Life Example of C++ Class

Let us understand the concept of classes with the help of a real-life example:

Suppose you are the manager of the stock of a biscuit manufacturing department. You have to keep a record of the item code of a product, item name, item price, number of items available, discount on each item, and perform the function of calculating the total price of the item by calculating its discount based on its price.

Here, the item details and functions to calculate the total price of the product are logically related. It would be a good practice to club them together under one single unit with the help of classes.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Using classes, not only could you group the data into a single unit, but also keep it secure with the help of access specifiers so that other manufacturing departments such as chips and sweets would not be able to access the information of the biscuit manufacturing department.

3. Significance of Class in C++

With the increase in demand from the information technology sector, a need was felt to design software that could be analogous to real-time entities. This need was fulfilled to a certain extent by structures in C, but structures were just halfway there.

With the introduction of classes and objects in C++, this problem was completely resolved. A proper establishment to solve real-time problems came with classes.

Here are some of the features of class that would help you acknowledge its significance:

3. Syntax of Class in C++

Now that we have received some motivation to learn about classes and objects in C++, let us take our first step towards understanding it. The syntax portion of classes would cover how to declare and define a class.

3.1 Declaration

There are basically four attributes that associate with the class declaration. They are as follows:

  1. Data elements – Data elements are nothing but logically related variables declared under one roof, that is, the class to store values with the help of objects to perform various operations such as read, write, display, modify or functions that require calculations or manipulation.
  2. Member functions – Member functions are nothing but simply functions that are declared inside a class. We use it to perform a set of operations that may be applied to objects of a particular class.
  3. Access specifiers – Access specifiers help you define the mode in which the data elements and member functions of a class can be accessed outside the class.
  4. The tag name of the class – The tag name of the class specifies the type of objects to be created for a particular class.

Key takeaway: The class definition describes the data members and member functions of the class whereas the class method describes how some class members functions are to be implemented.

3.2 Definition

Given below is the generalized way to define a class:

class class_name
{
private:

// declaration of variables
// declaration of functions

protected:

// declaration of variables
// declaration of functions

public:

// declaration of variables
// declaration of functions

};

Let us understand each keyword step by step:

  1. class  – It is a keyword that specified the implementation of a class.
  2. class_name  – It is the tag name of the class according to which the object is created.
  3. ; – Afterall a class is a user-defined entity, therefore it should be terminated with the help of a semicolon.
  4. Body of the class – A class can contain any three access specifiers, that is, public, private and protected. Let us look at what these access specifiers do:

Key takeaway: It is important to note that all the data members and member functions inside a class are private by default.

3.3 Method Definition

Simply declaring and defining the class wouldn’t serve the purpose. You need to provide a method definition in order to access the data members and member functions of the class.
In C++, we can define member functions in two ways: either inside or outside the class.

Let us understand how to define them in detail:

3.3.1 Outside the class

Here, you define the member function outside the class with the help of the scope resolution operator ‘::’.

class_name :: function_name

Here, the name of the class specifies that the function specified by the name of the function is a member of the class class_name.
The scope resolution operator specifies the scope of the function which is restricted to the class class_name.

This is how you would define the member function outside the class:

return_type class_name :: function_name (argument_1, argument_2,.., argument_n)
{
.

// Body of the function

.
}

3.3.2 Inside the class

You do not need to use the scope resolution operator while defining the member function.

This is how you would define a function inside the class.

class class_name
{
// variable declaration

/* function defintion */

void function_name( argument_1, argument_2,.., argument_n )
{

.
// Body of the function
.
}
};

Key takeaway: You can infer that the class declaration in C++ is quite similar to the declaration of a structure in C.

Here is a code in C++ that illustrates the implementation of classes:

#include<iostream>
using namespace std; 
class DataFlair 
{ 
public: 
string line; 
void display() 
{ 
cout<<"The message is: "<<line<<endl;
} 
}; 

int main() 
{ 

DataFlair object; // declaring a object of type DataFlair

object.line = "Welcome to DataFlair tutorials!"; 
object.display(); 
return 0; 
}

Code- 

Output-

4. Creating a Reference of Class Members in C++

So far, we saw how to declare and define the data members and member functions of a class. But, this is not the end of the story. Unless you reference the components of the class, you cannot use its data members and member functions to read, write, modify or perform manipulation operations.

This is done with the help of objects.

For instance,

class_name object_1, object_2, …. , object_n;

In order to create objects, the name of the class is followed by the name of the objects.

Let us consider a real-time example:

Suppose you have created a class “Stock” to keep a record of the name of the item, its ID and price. Then, you need to create the objects according to the requirement of the task given at hand

For instance,

Stock s1, s2;

Here, you have created 2 objects s1 and s2 of class “Stock”.

Key takeaway: In C++, we refer to class variables as objects.

We give reference to the members of the class using objects of the class.

Let us take a simple example to multiply and divide 2 numbers using classes:

class Operation
{
int number1, number2;
public:
int multiply (int n1, int n2)
{
int result = n1 * n2;
return result;
}
int divide (int n1, int n2)
{
if( n2 != 0 )
{
int result = n1 / n2;
return result;
}
}
};

/*o1 and o2 are objects of class Operation for multiplication and division respectively */

Operation o1, o2;

Elucidation

5. Array within a Class in C++

Let us consider a situation where we want to perform several functions by taking into account different parameters in each case. Using the conventional method, you would need to do thing same thing n number of times.

Therefore, C++ introduces the concept of defining an array within the class.
Declaring an array within a class can be done in either of the three modes: public, private or protected.

If we declare an array in a class in private mode, it can only be accessed inside the class as you can’t use functions to access it. It is preferable to declare an array in a class in public mode so that it can directly be accessed with the help of object(s).

Consider a problem where you have read and print the roll number and you have to read and display the marks of 5 subjects of a student along with its final percentage.
You can easily solve this problem by using an array within a class.

Let us understand the concept of arrays within a class keeping in mind the above-stated problem with the help of a C++ program:

#include<iostream>
using namespace std;
class Student
{
// Both the variables are private by default
int roll_no;
int marks[5];
public:
void getdata(); // Function to access both the private members of the class
void percentage(); // Function to calculate the final percentage of the student
};

void Student :: getdata ()
{
int i;
cout<<"Enter the roll number: ";
cin>>roll_no;
cout<<"Enter the marks "<<endl;
for(i = 0; i < 5; i++)
{
cout<<"Subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
}
void Student::percentage() // Function definition for finding final percentage
{
int i, total=0;
for(i = 0; i < 5; i++)
total = total + marks[i];
cout<<"The final percentage is "<<(total/5)<<"%"<<endl;
}

int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl;
Student s;
s.getdata();
s.percentage();
return 0;
}

Code- 

Output-

6. Object in C++

We are already well-acquainted with the term “Objects”.But, let us formally define objects.
In programming terminology, an object is basically a variable of a user-defined data type, that is, a class. In simple words, a class acts as a data type and an object acts as its variable.

We will discuss how memory allocation of objects takes place, how can array of objects be used, how to pass objects as function arguments, and how to functions return objects.

It is pretty clear that unless you create an object, you cannot access the members of a class. Thus, it is of utmost importance to create objects. If we do not create an object, simply the specification of information to be stored in a class would take place. There would be no implementation stage.

We can create objects with the help of the class name followed by the name of the object.

The basic syntax of creating an object is:

class_name object_1, object_2, object_3 …… object_n;

Here is a code in C++ that illustrates the implementation of a class using objects:

#include<iostream>
using namespace std;
class Product
{
//private by default
string item_name;
public:
void read(string item)
{
item_name = item;
}
void display()
{
cout<<"The item is: "<<item_name<<endl;
}
};
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Product p1, p2; // p1 and p2 are objects of the class Product

p1.read("Tea"); // The function read is invoked through the object p1
p1.display(); // The function display is invoked through the object p1

p2.read("Coffee"); // The function read is invoked through the object p2
p2.display(); // The function display is invoked through the object p2

return 0;
}

Code-

Output-

In the above program, after we define the class Product,

The statement:

Product p1, p2;

indicates to the C++ compiler that it has to create 2 objects of type Product in the computer memory.

Thereafter, the statements:

p1.read(“Tea”);
p1.display();

Tells the C++ compiler to invoke the functions read(string item) and display()

Similarly, with the help of p2, the C++ compiler invokes the same functions once again.

Now, let us discuss how memory allocation of objects takes place:

As we already discussed, we can instruct the C++ compiler to allocate computer memory for objects just by clearing them.

Now, let us discuss what is meant by an array of objects.

Instead of creating several objects to perform all the operations of type class_name, we can implement the concept of an array of objects.

Consider a case where you want to display the name of 10 items of a class Store. You can easily solve this problem with the help of an array of objects,

Here is a code in C++ that illustrates the implementation of an array of objects with reference to the above-states problem:

#include<iostream>
using namespace std;
class Store
{
//private by default
string item_name;
public:
void read(string item)
{
item_name = item;
}
void display()
{
cout<<"The item is: "<<item_name<<endl;
}
};
const int size = 10; 
Store order[size]; // Size of array of objects = 10

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

string ITEM;
int i;
// TAKING INPUT
for(i = 0; i < size; i++)
{
cout<<"Enter item name: ";
cin>>ITEM;
order[i].read(ITEM);
}
// DISPLAYING OUTPUT
for(i = 0; i < size; i++)
{
cout<<"Item"<<i+1<<endl;
order[i].display();
}
return 0;
}

Code-

Output-

7. Types of Objects in C++

In C++, there are basically 2 types of objects:

8. Types of Class Functions in C++

We may categorize class functions into three broad categories:

  1. Accessors: Accessor functions as those functions that allow the programmer to access the data members of the object. However, these functions do not have the provision to change the value of data members.
  2. Mutators: Mutator functions allows the programmer to change the data members of an object.
  3. Managers: Manager functions are basically functions that have specific functions like constructors and destructors to initialize and destroy class instances.

9. Static Class Member in C++

We will discuss both static data members and static member functions in detail.

9.1 Static data member

Just like a standard C++ program has global variables, a class has a static data member. It clearly means that the data member with static keyword is globally accessible to the class. We use static data members to generally store the common values to the entire class.

Key takeaway:

In order to make a data member static, we need to declare it within the class definition but define it outside the class definition.

Declaration

This is how we can declare a static data member:

class Class_name
{
static int var; // Declaring static data member inside the class

// BODY OF THE CLASS

};

Definition

This is how we can define a static data member:

int Class_name :: var; // Defining static data member outside the class

Key takeaway: It is possible to initialize the value of a static data member outside the class, that is, during its definition.

9.2 Static member function

A static member function is nothing but a function that has access to only the static data members in a class. It is invoked with the help of the name of the class rather than an object.

This is how we can declare a static member function:

class Class_name
{
static int var;

// BODY OF THE CLASS

static void display()
{
cout<<”The value of the variable is: ”<<var<<endl;
}
};
int Class_name :: var; // Invoking the static member function

In order to better understand the use of static members in a class, let us consider a situation in which we want to count the number of items dispatched to a store by entering its record.

Here is a code in C++ that illustrates the use of static members in a class with reference to the above-states problem:

#include<iostream>
using namespace std;

class Store
{
// private by default
int item_ID;
string item_name;
static int count;

public:
void read(int ID, string item)
{
item_ID = ID;
item_name = item;
count++;
}

void display()
{
cout<<"The item ID is: "<<item_ID<<endl;
cout<<"The item name is: "<<item_name<<endl;
}

// Static member function
static void item_count()
{
cout<<"The number of items are: "<<count<<endl;
}
};

int Store:: count =0; // Static data member invoked through class name

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Store s1, s2;
s1.read(1001,"Bucket");;
s2.read(1005,"Mug");
Store :: item_count();
s1.display();
s2.display();

return 0;
}

Code-

Output-

10 Difference Between Class and Structure

Here is a table that illustrates the difference between a structure and a class:

Structure Class 
All the members of a structure are public by default.
All the members of a class are private by default
Structures do not support any features of object-oriented programming.
Classes support the features of object-oriented programming like data abstraction, data encapsulation, polymorphism, and inheritance.
Structures may be implemented in both C and C++ programming languages.
Classes cannot be implemented in C. They can only be implemented in C++.
The members of a structure cannot be private or protected.
The members of a class can be private or protected.
A structure can contain only data members and not member functions.
A class can contain both data members and member functions.
We cannot directly initialize a value to the members of a structure.
 We can directly initialize a value to the members of a class.

After developing an understanding of the differences between structures and classes, it is pretty clear that classes are way better than structures in all respects.

11. Quiz on C++ Class and Object

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include <iostream>

     

    using namespace std;

    class test{

        public:

        int x;

    };

    int main()

    {

        test t;

        t.x=2;

        cout<<t.x;

        return 0;

    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include <iostream>

     

    using namespace std;

    class test{

        public:

        int x=5;

    };

    int main()

    {

        test t;

        cout<<t.x;

        return 0;

    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include <iostream>

     

    using namespace std;

    class test{

        int x;

        public:

        int y;

        test()

        {

            x=y=3;

        }

    };

    int main()

    {

        test t;

        cout<<t.x;

        return 0;

    }

     

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include <iostream>

     

    using namespace std;

    class test{

        int x;

        public:

        int y;

        test()

        {

            x=6;y=3;

            cout<<x;

        }

    };

    int main()

    {

        test t;

        cout<<t.y;

        return 0;

    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include <iostream>

     

    using namespace std;

    class test{

        int x;

        public:

        int y;

        test()

        {

            x=6;y=3;

            cout<<y<<x;

        }

    };

    int main()

    {

        test t;

        return 0;

    }

     

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include <iostream>

     

    using namespace std;

    class test{

        int x;

        public:

        int y;

        test(int i)

        {

            x=i;

            cout<<x;

        }

        test()

        {

            y=3;

            cout<<y;

        }

    };

    int main()

    {

        test t;

        return 0;

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include <iostream>

     

    using namespace std;

    class test{

        int x;

        public:

        int y;

        test(int i)

        {

            x=i;

            cout<<x;

        }

        test()

        {

            y=3;

            cout<<y;

        }

    };

    int main()

    {

        test t;

        test t1(10);

        return 0;

    }

     

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include <iostream>

     

    using namespace std;

    class test{

        public:

        int x;

        int y;

        int print()

        {

            cout<<x<<y;

        }

    };

    int main()

    {

        test t;

        t.x=t.y=5;

        t.print();

        return 0;

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include <iostream>

    #include <string>

    using namespace std;

    class student{

        public:

        string name=”John”;

        int Rollno=10;

        int print()

        {

            cout<<name<<” “<<Rollno;

        }

    };

    int main()

    {

        student s;

        s.print();

        return 0;

    }

     

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include <iostream>

    #include <string>

    using namespace std;

    class student{

        public:

        string name=”John”;

        int Rollno=10;

        student()

        {

            cout<<Rollno;

        }

    };

    int main()

    {

        student s;

        return 0;

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    Objects are ?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Default access modifier in a class is?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

     What statement is true with respect to memory allocation in class?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    What if no constructor is defined explicitly in a class?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    What is not true with respect to class?

    Correct
    Incorrect

12. Summary

In this tutorial, we discussed the prime concept of object-oriented programming- classes and objects. We inferred that C++ without classes is of no importance after shedding light on the significance of classes and objects.

Thereafter, we discussed the syntax of a class in detail by covering its definition, declaration, and method definition. We even saw how important it is to reference the variables of the class in order to access it. We carried on our discussion by studying array within classes with the help of an illustrative program.

Doubts are welcome in the comments section, our experts will assist you in the best possible way.

Install C++ on Linux in just 2 Min and 14 Seconds

Exit mobile version