In this tutorial, you will learn the essentials of classes and objects in C++, including their definition, features, and practical implementation. You will also explore the fundamental concepts of object-oriented programming, understand the differences between classes and objects, and delve into examples to solidify your understanding of how these concepts are applied in real-world programming.
Contents:
- What are Classes in C++?
- Defining a Class in C++
- What are Objects in C++?
- Creating Objects in C++
- Features of Classes in C++
- Features of Object-Oriented Programming in C++
- Access Specifiers in C++
- Differences Between Classes and Objects in C++
- Classes and Objects Examples in C++
- FAQs on C++ Classes and Objects
What are Classes in C++?
Classes are the building blocks of object-oriented programming. Classes are user defined datatypes that can hold multiple data members of any data type and member functions to operate on them.
- A class defines the structure for its objects. We can say that class is the blueprint for its objects. All objects of the same class have the same member functions and data members with different values.
- A can have multiple data members of different datatypes to store information and many members function to manipulate its data members.
- Classes in C++ are used to implement features of object-oriented programming like data abstraction, inheritance, polymorphism, encapsulation etc in C++.
- Classes in C++ are used to make the code replicate real world functionalities better. This is so because objects of a class in C++ can resemble real life objects that can be classified into groups.
Defining a Class in C++
Syntax of a Class:
Here’s the basic syntax for defining a class in C++:
class ClassName { public: // data members (variables) // member functions (methods) };
Example:
#include <iostream> using namespace std; // Define a class named Quiz class Quiz { public: int totalMarks; // data member void displayMarks() { // member function cout << "Total Marks: " << totalMarks << endl; } };
What are Objects in C++?
An object is an instance of a class. A class can have multiple objects. A class can be brought to use only by having objects of that class or it’s child classes.
- A class takes up no space in memory. Memory is allocated only when an object is created. Memory is allocated according to the data members defined inside the class.
- The data members and member functions of an object can be accessed using the dot(‘.’) operator with the object name.
- Objects represent real life entities. For example, for a class ‘Girls’ we can have multiple objects like Sara, Tina, Amy with characteristics like height, weight, complexion and methods eating, sleeping, talking, walking etc.
- All objects of the same class have the same member functions and data members saved separately with different values unless the member is static. Static members are saved only once and used for all objects.
Creating Objects in C++
In C++, once you define a class, you can create objects of that class. An object is an instance of a class, and it holds its own copy of data members and can use the class’s functions.
Syntax for Creating Objects:
ClassName objectName;You can create multiple objects like:
ClassName obj1, obj2, obj3;Example:
#include <iostream> using namespace std; // Define a class called Quiz class Quiz { public: int score; void showScore() { cout << "Score: " << score << endl; } }; int main() { Quiz q1, q2; // Creating two objects of class Quiz q1.score = 80; q2.score = 95; q1.showScore(); // Output: Score: 80 q2.showScore(); // Output: Score: 95 return 0; }
Output:
Score: 80 Score: 95
This C++ program defines a class called Quiz with a public variable score and a function showScore() to display it. In main(), two objects q1 and q2 are created. Their scores are set directly, and showScore() is called for each to print their individual scores. This shows how objects hold separate data and use class functions to display it.
Features of Classes in C++
Classes are used to implement object-oriented programming in C++. Here are some features of classes in C++.
- A class in C++ can have multiple parent classes and multiple child classes. This means C++ supports inheritance.
- Data members and member functions in a class can be given different levels of security by the use of access specifiers. By default, all data members and member functions of a class are private.
- A class has no size of its own. It is just an abstract data structure that can be used to define objects. Memory is allocated as soon as a new object is created.
- Classes in C++ can have other classes defined inside them too. This feature is known as nesting of classes.
Features of Object-Oriented Programming in C++
Being an object-oriented programming language is the main reason why C++ has an edge over its ancestor C language. Here are some features of object-oriented programming in C++.
- Polymorphism: Polymorphism means having many forms. In C++, polymorphism is implemented by the function overloading and operator overloading.
- Encapsulation: Encapsulation can be defined as wrapping up of data and information under a single unit. In C++, Encapsulation is implemented by binding together the data and the functions that manipulate them in the form of a class.
- Inheritance: The capability of a class to derive features and functionalities from other classes is called Inheritance.
- Data Abstraction: Abstraction refers to displaying only essential information while hiding the background details. In C++, data abstraction is implemented with the use of access specifiers.
Access Specifiers in C++
Access specifiers define how members (variables and functions) of a class can be accessed.
There are three main types:
- public: Members are accessible from anywhere (inside or outside the class). Most commonly used for functions.
- private: Members are accessible only inside the class. Default access specifier (if none is given).
- protected: Members are like private, but can also be accessed in derived (child) classes.
Example:
#include <iostream> using namespace std; class Quiz { public: int totalQuestions; // public: accessible anywhere private: int correctAnswers; // private: only accessible inside the class protected: int bonusMarks; // protected: accessible in derived class public: void setResults(int correct, int bonus) { correctAnswers = correct; // allowed: private accessed inside class bonusMarks = bonus; // allowed: protected accessed inside class } void showResults() { cout << "Correct Answers: " << correctAnswers << endl; cout << "Bonus Marks: " << bonusMarks << endl; } }; // Derived class to access protected member class AdvancedQuiz : public Quiz { public: void showBonus() { cout << "Bonus Marks (from derived class): " << bonusMarks << endl; } }; int main() { Quiz q; q.totalQuestions = 10; q.setResults(8, 5); q.showResults(); AdvancedQuiz aq; aq.setResults(9, 7); aq.showBonus(); return 0; }
Output:
Correct Answers: 8 Bonus Marks: 5 Bonus Marks (from derived class): 7
This C++ program shows access specifiers in a class: public, private, and protected. The Quiz class has totalQuestions as public (can be accessed anywhere), correctAnswers as private (only inside the class), and bonusMarks as protected (accessible in derived classes). The setResults() function sets values, and showResults() displays them. The AdvancedQuiz class inherits from Quiz and uses the protected bonusMarks in its own function. In main(), both base and derived class objects are used to show how access levels work.
Differences Between Classes and Objects in C++
This table summarizes the key differences between classes and objects, highlighting their roles in object-oriented programming.
| Aspect | Class | Object |
|---|---|---|
| Definition | A blueprint or template defining the structure and behavior of objects. | An instance of a class, representing a specific entity with state and behavior. |
| Nature | Abstract; a logical construct. | Concrete; a physical entity. |
| Usage | Used to define properties and methods for objects. | Used to perform actions and store data based on the class definition. |
| Memory Allocation | Does not consume memory for attributes or methods. | Consumes memory for its attributes when instantiated. |
| Declaration | Declared using the `class` keyword (e.g., `class Car {…}`). | Created by instantiating a class (e.g., `Car myCar = new Car();`). |
| Identity | Acts as a template; multiple instances (objects) can be created from it. | Each object has a unique identity and its own state. |
| Example | `class Car { color; speed; drive(); stop(); }` | `Car myCar = new Car();` |
Classes and Objects Examples in C++
Example 1: Object Declaration Before Class
#include<iostream> using namespace std; int main() { c1 obj; cout<<obj.a; } class c1 { int a=10; };
The code gives an error because the object obj is declared before the class c1 is defined. In C++, you must define the class before creating an object of that class.
Example 2: Size of an Object
#include<iostream> using namespace std; class c1 { int a[10]; char b; }; int main() { c1 obj; cout<<sizeof(obj); }
Output:
44
The size of the object obj is the sum of the sizes of its data members. Here, a is an array of 10 integers and b is a char, contributing to the total size of 44 bytes.
Example 3: Size of an Object vs. Size of Data Member
#include<iostream> using namespace std; class c1 { public: int a[10]; }; int main() { c1 obj; bool ans=sizeof(obj)==sizeof(obj.a); cout<<ans; }
The given code will give an error. The size of an object is equal to the sum of sizes of its data members. Here, since the object obj has only 1 data member ‘a’ thus, the size of obj is equal to size of ‘a’.
Example 4: Size of a Class with String Data Member
#include<iostream> using namespace std; class c1 { string s; }; int main() { c1 obj; cout<<sizeof(obj); }
Output:
32
The size of the object obj is 32 bytes, which is the default size for a string data member in most implementations.
Example 5: String Initialization in Class
#include<iostream> using namespace std; class c1 { string s="sanfoundary"; }; int main() { c1 obj; cout<<sizeof(obj); }
Output:
32
Even though the string data member s is initialized with a value, the size of the object remains 32 bytes.
Example 6: Accessing Private Data Member
#include<iostream> using namespace std; class c1 { string s[2]; }; int main() { c1 obj; cout<<sizeof(obj.s); }
The given code gives an error because s being a private member cannot be accessed outside the class c1. Here, sizeof() is trying to access s.
Example 7: Array Size in Class
#include<bits/stdc++.h> using namespace std; class c1 { int arr[]={1,2,3}; }; int main() { c1 obj; cout<<sizeof(obj); }
The given code gives an error because an array cannot be declared as a data member inside a class without mentioning its size.
Example 8: Default Values for Data Members
#include<bits/stdc++.h> using namespace std; class c1 { public: string s="sanfoundry"; }; int main() { c1 obj; cout<<obj.s; }
Output:
sanfoundry
Data members can be given default values. Here, s is initialized to “sanfoundry” and printed in the main function.
FAQs on C++ Classes and Objects
1. What is a class in C++?
A class in C++ is a user-defined data type that groups data and functions into a single unit. It’s like a blueprint from which objects are created.
2. What is an object in C++?
An object is an instance of a class. It holds actual values and allows access to the class’s member variables and functions.
3. Can we define functions inside a class?
Yes. These are called member functions. You can define them either inside the class or outside using the scope resolution operator ::.
4. What is the size of an empty class object in C++?
Even an empty class occupies at least 1 byte of memory. This is required to ensure each object has a unique memory address.
5. Can you pass objects to functions?
Yes, you can pass objects to functions to share or modify their data, depending on how you pass them—by value, reference, or pointer.
6. What are the benefits of using classes and objects?
They help organize code better, promote reusability, support data hiding, and allow the creation of complex applications using object-oriented principles.
7. What is the dot operator in C++ (used with objects)?
The dot operator is used to access the members (variables or functions) of an object. For example, to use or modify a property of an object.
8. Can multiple objects be created from one class?
Absolutely. You can create as many objects as needed from a single class, and each object will maintain its own data.
Key Points to Remember
Here is the list of key points we need to remember about “C++ Classes and Objects”.
- Classes in C++ serve as blueprints for objects, defining the structure and behavior of the objects they create, with multiple data members and member functions.
- An object is an instance of a class and takes up memory space only when created. Objects of the same class share the same member functions and data members but store different values.
- Classes in C++ enable object-oriented programming features like inheritance, polymorphism, encapsulation, and data abstraction, allowing for real-world modeling in code.
- Memory is allocated for the data members of a class only when an object is instantiated, and static members are shared across all objects of the class.
- Classes use access specifiers to control the visibility and security of data members and member functions, with the default being private, limiting access to within the class itself.
- Access specifiers in C++ are public, private, and protected, determining the accessibility of class members.