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

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:

  • Significance of class in C++
  • Syntax of a class
  • Creating reference of class members
  • Array within a class
  • Types of objects in C++
  • Types of class functions
  • Static class members
  • Difference between Class and Structure

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

C++ Class and Object

Keeping you updated with latest technology trends, Join DataFlair on Telegram

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.

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:

  • It helps you keep your data safe and secure from the outside world.
  • If we wish to grant access to certain data, it can be achieved with the help of access specifiers available in classes.
  • Classes support the concept of inheritance that reduces code redundancy and makes things easier for the programmer by allowing a derived class to directly inherit all the properties of the base class and enhances the readability of the code.
  • It allows you to club both data elements and the various functions associated with it under one unit.

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:
  • private: – It instructs the C compiler that all the data members and member functions declared within the private mode should not be accessible outside the class.
  • protected: – We shall deal with this keyword in detail in the inheritance tutorial.
  • public: – It instructs the C++ compiler that all the data members and member functions declared within the public mode should be accessible anywhere inside the C++ program.

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

Syntax of C++ Class

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- 

How to implement C++ Class

Output-

Output of Implementation of C++ Class

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

  • Here, both the variables number1 and number2 are private by default and hence cannot be accessed by the class. Therefore, we create a member function named multiply and divide in public mode to take both the arguments into consideration to perform the multiplication and division of both the numbers respectively with the help of 2 objects.
  • In order to multiply both the numbers, we need to call the function and multiply inside the main function as follows:o1. multiply( argument1, argument2 );
  • In order to divide the first number with the second one, we need to call the function and divide inside the main function as follows:o2.divide( argument1, argument2 );

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- 

Example of Array within a Class in C++

Output-

Output of Array within a Class in C++

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-

implementation of Class Using Object in C++

Output-

Output of class using objects in C++

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.

Memory Allocation of Objects in C++

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-

Use Array in C++ Object

Output-

implementation of an array of objects in C++ with Output

7. Types of Objects in C++

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

  • Global object – As the name itself suggests, we declare a global object outside all the function bodies. It means that the object is globally accessible to all the member functions of the class in the program. In simple words, a global object is accessible anywhere in the program.
  • Local object – As the name itself suggests, the scope of the object is local. We declare a local object within a function. It means that the local object is only available to the function that declares it. We cannot use it outside the function that has declared it.

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:

  • The entire class maintains only a single copy of a static data member which all the objects of that class share.
  • A static data member is only visible inside the class.

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-

 Static members in C++ class

Output-

 static members in C++ class with Output

10 Difference Between Class and Structure

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

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

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.