Top C++ Interview Questions and Answers (2025)
Question: What are classes and objects in C++?
Answer:
In C++, classes and objects are the fundamental building blocks of Object-Oriented Programming (OOP). They provide a way to model real-world entities, organize code, and define behaviors.
1. Class in C++:
A class is a blueprint or template for creating objects. It defines the properties (attributes) and methods (functions) that objects created from the class will have. Classes encapsulate data for the object and provide methods to manipulate that data.
Syntax:
class ClassName {
public:
// Data members (attributes)
int attribute1;
float attribute2;
// Member functions (methods)
void method1() {
// method code
}
void method2() {
// method code
}
};
A class is a user-defined data type that can contain:
- Data Members (attributes or properties) - These represent the state or characteristics of an object.
- Member Functions (methods or behaviors) - These represent the actions that can be performed on an object.
Example of a Class:
class Car {
public:
// Data members
string make;
string model;
int year;
// Member function
void startEngine() {
cout << "Engine started!" << endl;
}
void stopEngine() {
cout << "Engine stopped!" << endl;
}
};
In this example, the Car
class has three data members (make
, model
, year
) and two member functions (startEngine
, stopEngine
).
2. Object in C++:
An object is an instance of a class. When you create an object, the class is instantiated into memory, and the object can now use the properties and methods defined by the class.
Objects are created using the class constructor. Multiple objects can be created from the same class, each with its own set of attributes.
Syntax to Create an Object:
ClassName objectName;
Example of Creating and Using an Object:
int main() {
// Creating an object of class Car
Car myCar;
// Assigning values to attributes
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;
// Calling member functions using the object
myCar.startEngine();
myCar.stopEngine();
cout << "Car make: " << myCar.make << endl;
cout << "Car model: " << myCar.model << endl;
cout << "Car year: " << myCar.year << endl;
return 0;
}
In this example:
myCar
is an object of theCar
class.- The object
myCar
has its own copy of the attributes (make
,model
,year
) and can call the member functions (startEngine
,stopEngine
).
Key Concepts of Classes and Objects in C++:
-
Encapsulation:
- Classes encapsulate data (attributes) and functions (methods) into a single unit.
- Encapsulation hides the implementation details of a class and exposes only necessary information.
- Access control is used through access specifiers (
public
,private
,protected
).
class Person { private: string name; int age; public: void setName(string n) { name = n; } void setAge(int a) { age = a; } void displayInfo() { cout << "Name: " << name << ", Age: " << age << endl; } };
In this example, the
name
andage
attributes are private, meaning they cannot be accessed directly from outside the class. They can only be modified through the public methodssetName
andsetAge
. -
Constructor:
- A constructor is a special member function that is called automatically when an object is created. It is used to initialize the object’s attributes.
- Constructors have the same name as the class and do not have a return type.
class Rectangle { public: int length, width; // Constructor Rectangle(int l, int w) { length = l; width = w; } int area() { return length * width; } };
In this example, the
Rectangle
class has a constructor that initializes thelength
andwidth
attributes when an object is created. -
Destructor:
- A destructor is a special member function that is called when an object is destroyed. It is used to release resources allocated during the object’s lifetime (e.g., memory).
- Destructors have the same name as the class but are prefixed with a tilde (
~
).
class MyClass { public: // Destructor ~MyClass() { cout << "Object destroyed!" << endl; } };
The destructor in this example prints a message when an object of
MyClass
is destroyed. -
Access Specifiers:
- public: Members are accessible from outside the class.
- private: Members are not accessible from outside the class; they are only accessible within the class.
- protected: Members are accessible within the class and by derived classes.
class Example { public: int publicVar; // Can be accessed from anywhere private: int privateVar; // Cannot be accessed from outside the class };
-
Inheritance:
- Inheritance allows one class to inherit properties and behaviors (methods) from another class. It enables the creation of a new class (derived class) based on an existing class (base class).
class Animal { public: void eat() { cout << "Animal is eating." << endl; } }; class Dog : public Animal { public: void bark() { cout << "Dog is barking." << endl; } };
Here,
Dog
is a derived class that inherits theeat
method from theAnimal
base class. -
Polymorphism:
- Polymorphism allows functions or methods to behave differently based on the object that invokes them. This is achieved through method overriding and method overloading.
-
Abstraction:
- Abstraction allows hiding the complex implementation details and exposing only the essential features. Abstract classes and pure virtual functions are used to achieve abstraction.
Summary:
- Classes define the structure and behavior (methods) of objects.
- Objects are instances of classes, created based on the class template.
- Classes help achieve encapsulation, abstraction, and inheritance, forming the core of Object-Oriented Programming in C++.
Question: What is the difference between Call by Value and Call by Reference in C++?
Answer:
In C++, Call by Value and Call by Reference are two methods used to pass arguments to functions. They determine how arguments are passed to functions and how changes to the parameters in the function affect the original arguments.
1. Call by Value:
- In Call by Value, a copy of the actual argument is passed to the function. The formal parameter in the function gets its own copy of the value and does not affect the actual argument.
- Changes made to the parameter inside the function do not affect the original variable in the calling function.
Key Characteristics:
- A copy of the argument is passed to the function.
- Changes to the parameter do not affect the original argument.
- Generally used for small, simple data types where passing by value does not have significant performance overhead.
Example:
#include <iostream>
using namespace std;
void addTen(int num) {
num += 10; // This change will not affect the original variable
cout << "Inside function: " << num << endl;
}
int main() {
int x = 5;
addTen(x);
cout << "After function call: " << x << endl; // Original variable x remains unchanged
return 0;
}
Output:
Inside function: 15
After function call: 5
Here, the value of x
remains unchanged in the main
function because only a copy of x
is passed to addTen
.
2. Call by Reference:
- In Call by Reference, instead of passing a copy of the argument, the reference (or address) of the actual argument is passed to the function. This allows the function to modify the original argument.
- Changes made to the parameter inside the function will directly affect the actual argument in the calling function.
Key Characteristics:
- The reference to the argument (memory address) is passed to the function.
- Changes to the parameter affect the original argument.
- Generally used when large data structures or objects are involved, to avoid the overhead of copying data.
Example:
#include <iostream>
using namespace std;
void addTen(int &num) {
num += 10; // This change will affect the original variable
cout << "Inside function: " << num << endl;
}
int main() {
int x = 5;
addTen(x);
cout << "After function call: " << x << endl; // Original variable x is changed
return 0;
}
Output:
Inside function: 15
After function call: 15
In this case, the value of x
is modified in the main
function because the reference to x
is passed to addTen
, allowing the function to change the original variable.
Key Differences:
Feature | Call by Value | Call by Reference |
---|---|---|
Argument Passing | A copy of the argument is passed. | A reference (address) of the argument is passed. |
Effect on Original | Changes in the function do not affect the original variable. | Changes in the function affect the original variable. |
Memory Usage | More memory is used as a copy of the argument is created. | Less memory is used since only a reference (address) is passed. |
Performance | Can be slower when passing large data (e.g., large objects or arrays) due to copying. | More efficient when dealing with large data as no copying occurs. |
Use Case | When you do not want the original data to be modified. | When you need to modify the original data or pass large objects without copying them. |
When to Use:
- Call by Value: Use when the function doesn’t need to modify the argument, or when the argument is a small data type (like
int
,char
, etc.), and performance is not a concern. - Call by Reference: Use when you need the function to modify the argument, or when you’re dealing with large data types or complex objects where copying would be inefficient.
In summary:
- Call by Value creates a copy, leaving the original data untouched.
- Call by Reference directly manipulates the original data by passing a reference.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as C++ interview questions, C++ interview experiences, and details about various C++ job positions. Click here to check it out.
Tags
- C++
- C++ interview questions
- C++ constructors
- Inline keyword
- Reference in C++
- Class and object in C++
- Call by value vs call by reference
- Abstract class
- Virtual functions
- New vs malloc
- This pointer in C++
- C++ templates
- C++ struct vs class
- Exception handling in C++
- Operator overloading in C++
- Polymorphism in C++
- C++ pointers
- C++ iterators
- C++ STL
- Scope resolution operator
- C++ memory management
- C++ exception handling
- C++ overloading
- C++ function overriding