×

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we would be looking forward to discussing object classes. But before going any further, let us discover what classes and objects are.

C++ Class

In C++, a class is the basic building block that leads to object-oriented programming. Class is user-defined data that has its data members and member functions. These members can be easily accessed by creating an instance of that class. In popular terms, the class is a blueprint for an object. A typical class syntax looks like the following:

 class Animals   
 {   
      public: 
      int category;                   //field or data member    
      float population;         //field or data member 
      String name;                   //field or data member   
  }    

Note: Whenever a class is defined, no memory is allocated. But when the field or data members are initialized inside a class, memory is allocated.

C++ Object

In C++, an object is an entity of a class. It is also called an instance of the class. In simple words, an object is a real-world entity. The entities can be anything like cars, bars, mobiles, tablets, etc. An object always has a state and behavior. By state, we mean data, and by behavior, we mean functionality. An object in C++ typically looks like:

 Animal a1 ;
 // creating an object of class Animal 

Now that we have seen how class and objects look, let’s look at an example to understand how class and object work together.

Class and Object

 #include <bits/stdc++.h>
 using namespace std; 
 class Animals
 { 
    public: 
       int population;
       string name;
 }; 
 int main() { 
     Animals a1;   
     a1.population = 2000;   
     a1.name = "One-horned Rhino";  
     cout<<a1.population<<endl; 
     cout<<a1.name<<endl; 
     return 0; 
 }    

Output:

C++ Object Class

The above code is a classic example for implementing class and object in C++. We have defined a class Animals having data members population and name. We kept the data members public so that they are easily accessible. In the driver code, we have initialized these data members with some names and values and printed them on the console as output.

Class and Objects using Methods

 #include <bits/stdc++.h> 
 using namespace std; 
 class Animal { 
    public: 
        int population;   
        string name;    
        void push(int i, string n)   
         {   
             population = i;   
             name = n;   
         }   
        void show()   
   {  
             cout<<population<<"  "<<name<<endl;   
    }   
 }; 
 int main()
 { 
     Animal a1;
     Animal a2;
     a1.push(21, "Zebra");   
     a2.push(22, "Horse");   
     a1.show();   
     a2.show(); 
     return 0; 
 }  

Output:

C++ Object Class

The above code demonstrates the activity of class and object by using methods. Methods are nothing but functions that are defined inside the class Animal for some specific purpose. Here, we have defined two methods, namely, push and show. Push method inserts or assigns the values, and the show method is used to display the inserted values. To do this, we have made two objects, a1 and a2, to be associated with both methods. These objects access the values through methods and display them on the console.

Creating multiple Objects for same class

 #include<bits/stdc++.h>
 using namespace std;
 class SuperCar {
   public:
     string brand;  
     string model;
     int year;
 };
 int main() {
   SuperCar carObj1;    // creating object for car1
   carObj1.brand = "Lamborghini Aventador";
   carObj1.model = "Sunflex S2";
   carObj1.year = 2020;
   SuperCar carObj2;   // creating object for car2
   carObj2.brand = "Lycan HyperSport";
   carObj2.model = "Agira";
   carObj2.year = 1969;
   cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<endl;
   cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<endl;
   return 0;
 } 

Output:

C++ Object Class

In the above code, we have defined a class SuperCar with their data members brand, model, and a year respectively. We created two objects for the class SuperCar namely car Obj1 and car Obj2 which are then initialized by the values for the brand, model, and year.

The benefit of creating multiple objects is to make the class reusable. This enables the program to set or get multiple values using only a single class definition. Also, the properties of this class are reflected by creating multiple objects. In a similar sense, we created two objects in the program and then displayed the values associated with the object class.

Advantages

  1. The benefit of creating an object class is that the properties of one class can be accessible to its multiple objects.
  • The object class is that it increases code readability. The code is turned more easily to debug and implement.
  • Object class is an object-oriented methodology that follows strict rules which are needed while writing complex systems.
  • We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch, which is a procedure-oriented approach. This leads to saving of development time and higher productivity.
  • By creating an object class, we can easily manage different types of software complexity.

Related Topics

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

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

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.