Classes and Objects in C++
Classes and Objects in C++ Interview with follow-up questions
1. What are classes and objects in C++?
Class
A class is a user-defined type that bundles together data (member variables) and functions (member functions / methods) that operate on that data. It acts as a blueprint — it defines the structure and behaviour, but holds no data itself.
class BankAccount {
public:
BankAccount(std::string owner, double balance)
: owner_{std::move(owner)}, balance_{balance} {}
void deposit(double amount) { balance_ += amount; }
void withdraw(double amount) { balance_ -= amount; }
double balance() const { return balance_; }
private:
std::string owner_;
double balance_;
};
Object
An object is a specific instance of a class, occupying memory and holding its own state:
BankAccount alice{"Alice", 1000.0}; // stack object
alice.deposit(250.0);
std::cout << alice.balance(); // 1250.0
auto bob = std::make_unique("Bob", 500.0); // heap object
bob->deposit(100.0);
Key OOP concepts tied to classes and objects:
- Encapsulation:
private/protected/publicaccess specifiers hide implementation details. Only the public interface is visible to users. - Abstraction: The class exposes what an object does, not how it does it internally.
- Constructors / destructors: Special member functions that handle initialisation and cleanup. Follow the Rule of Five (C++11) if you manage resources manually: define or
= deletethe destructor, copy constructor, copy assignment, move constructor, and move assignment together. - RAII (Resource Acquisition Is Initialisation): Objects acquire resources in constructors and release them in destructors, making resource management exception-safe.
struct vs class:
The only language difference is the default access level: struct members are public by default; class members are private. By convention, struct is used for plain data aggregates (no invariants) and class for types with encapsulated invariants.
Common interview follow-up: "What is the difference between a class and an object?" — A class is a type definition (a compile-time concept); an object is a runtime instance of that type with its own storage and state.
Follow-up 1
What is a constructor and destructor in a class?
In C++, a constructor is a special member function of a class that is automatically called when an object of that class is created. It is used to initialize the object's data members. A destructor, on the other hand, is a special member function that is automatically called when an object is destroyed or goes out of scope. It is used to clean up any resources that the object may have acquired.
Follow-up 2
Can you explain the concept of class members?
In C++, class members are the variables and functions defined within a class. There are two types of class members: data members and member functions. Data members represent the properties or attributes of an object, while member functions define the behaviors or actions that an object can perform.
Follow-up 3
What is the difference between public, private, and protected members in a class?
In C++, class members can have different access specifiers: public, private, and protected. Public members are accessible from anywhere in the program. Private members can only be accessed within the class itself. Protected members are similar to private members, but they can also be accessed by derived classes.
Follow-up 4
How do you instantiate an object in C++?
To instantiate an object in C++, you need to use the 'new' keyword followed by the class name and parentheses. For example, if you have a class named 'MyClass', you can instantiate an object of that class using the following syntax:
MyClass* myObject = new MyClass();
2. How do you declare a class in C++?
A class is declared using the class (or struct) keyword, followed by the class name, a body enclosed in braces {}, and a terminating semicolon.
Basic syntax:
class ClassName {
public:
// Public interface: accessible from anywhere
ClassName(int value); // constructor
~ClassName(); // destructor
void doSomething(); // member function
int getValue() const; // const member function
protected:
// Accessible within this class and derived classes
int protectedData_;
private:
// Accessible only within this class
int value_;
};
Full example with definition:
class Rectangle {
public:
Rectangle(double width, double height)
: width_{width}, height_{height} {} // member initialiser list
double area() const { return width_ * height_; }
double perimeter() const { return 2 * (width_ + height_); }
private:
double width_;
double height_;
};
// Usage
Rectangle r{4.0, 3.0};
std::cout << r.area(); // 12.0
Key points interviewers expect:
- Member initialiser list (
: width_{width}) is preferred over assignment in the constructor body — it initialises members directly, avoiding a default-construct-then-assign pattern. constmember functions (postfixconst) promise not to modify the object; they can be called onconstobjects.- Access specifiers default to
privateforclass,publicforstruct. Members declared before the first access specifier get the default. - Semicolon after
}— easy to forget; omitting it is a common compile error. - The compiler auto-generates a default constructor, copy/move constructors, copy/move assignment operators, and a destructor only if you don't declare them yourself. If you declare a destructor, declare or
= default/= deletethe rest (Rule of Five).
C++11+ additions:
class Immutable {
public:
explicit Immutable(int v) : value_{v} {} // explicit prevents implicit conversion
int value() const { return value_; }
private:
const int value_;
};
expliciton single-argument constructors prevents unintended implicit conversions.= defaultand= deletelet you opt into or out of compiler-generated special member functions cleanly.
Follow-up 1
What is the syntax for declaring a class?
The syntax for declaring a class in C++ is as follows:
class ClassName {
// class members
};
Follow-up 2
Can you give an example of a class declaration?
Sure! Here is an example of a class declaration in C++:
class Person {
private:
string name;
int age;
public:
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
string getName() {
return name;
}
int getAge() {
return age;
}
};
Follow-up 3
What are the different parts of a class declaration?
A class declaration in C++ consists of the following parts:
- The
classkeyword - The name of the class
- The class members, which include data members and member functions
Here is an example of a class declaration with the different parts labeled:
class ClassName {
// class members
};
3. How do you access class members in C++?
Class members (data members and member functions) are accessed using one of two operators, depending on whether you have an object or a pointer to an object.
Dot operator . — use with objects and references
class Point {
public:
int x, y;
void print() const { std::cout << x << ", " << y << '\n'; }
};
Point p{3, 4};
p.x = 10; // access data member
p.print(); // call member function
Point& ref = p;
ref.x = 20; // same syntax through a reference
Arrow operator -> — use with pointers
Point* ptr = &p;
ptr->x = 5; // equivalent to (*ptr).x = 5
ptr->print();
// With smart pointers (same syntax)
auto sp = std::make_unique(1, 2);
sp->print();
sp->x = 99;
-> is just syntactic sugar for (*ptr).member. Smart pointers (unique_ptr, shared_ptr) overload -> so they behave exactly like raw pointers in this regard.
Access control and specifiers:
publicmembers are accessible from anywhere.privatemembers are accessible only from within the class itself andfrienddeclarations.protectedmembers are accessible within the class and its derived classes.
class Counter {
public:
void increment() { ++count_; } // public method can access private member
int value() const { return count_; }
private:
int count_ = 0;
};
Counter c;
c.increment();
// c.count_ = 5; // compile error: count_ is private
Accessing static members:
Static members belong to the class, not to any instance. Access them via the class name and scope resolution operator :: (or through an object, though the former is clearer):
class Config {
public:
static int maxConnections;
};
Config::maxConnections = 100; // preferred
Pointer-to-member operators .* and ->*:
Used when you have a pointer to a specific member (less common, but occasionally tested):
int Point::* mp = &Point::x;
std::cout << p.*mp; // access via object
std::cout << ptr->*mp; // access via pointer
Common interview gotcha: Calling a member function on a null pointer is undefined behaviour, even if the function doesn't access this. Always verify that a pointer is non-null before dereferencing.
Follow-up 1
What is the dot operator?
The dot operator (.) is used to access class members when working with objects or instances of a class. It is used with the object name followed by the member name. For example, objectName.memberName.
Follow-up 2
What is the arrow operator and when is it used?
The arrow operator (->) is used to access class members when working with pointers to objects. It is used with the pointer to the object followed by the member name. For example, pointerToObject->memberName.
Follow-up 3
Can you give an example of accessing class members?
Sure! Here's an example:
#include
class MyClass {
public:
int myVariable;
void myMethod() {
std::cout << "Hello, World!" << std::endl;
}
};
int main() {
MyClass obj;
obj.myVariable = 42;
obj.myMethod();
return 0;
}
In this example, we define a class MyClass with a public member variable myVariable and a public member function myMethod. We create an object obj of type MyClass and access its members using the dot operator.
4. What is the 'this' pointer in C++?
this is an implicitly available pointer inside every non-static member function. It points to the object on which the member function was called.
Type: ClassName* const (the pointer itself is const — you cannot reseat this; inside a const member function it becomes const ClassName* const).
Primary uses:
1. Disambiguate member variables from parameters with the same name
class Circle {
public:
Circle(double radius) : radius{radius} {} // member initialiser — cleaner
// or:
void setRadius(double radius) { this->radius = radius; } // this-> disambiguates
private:
double radius;
};
(Prefer the initialiser-list form or distinct naming conventions like radius_ to avoid needing this-> for disambiguation.)
2. Return the current object (enables method chaining)
class Builder {
public:
Builder& setName(std::string name) { name_ = std::move(name); return *this; }
Builder& setAge(int age) { age_ = age; return *this; }
Person build() const { return {name_, age_}; }
private:
std::string name_;
int age_{};
};
Person p = Builder{}.setName("Alice").setAge(30).build(); // fluent interface
3. Pass the current object to another function
void registerObject(Widget* w);
class Widget {
public:
void setup() { registerObject(this); }
};
4. Check for self-assignment in copy/move operators
MyClass& operator=(const MyClass& other) {
if (this == &other) return *this; // self-assignment guard
// ... copy members
return *this;
}
Key facts interviewers probe:
thisis not available in static member functions — they are not called on any specific object.thisis an rvalue in most expressions (you cannot take its address with&this).- In a
constmember function,thishas typeconst T*, so the function cannot modify data members (unless they are declaredmutable). - Storing
thisin a callback or container is dangerous if the object's lifetime ends before the callback fires — a common cause of dangling pointer bugs. Usestd::enable_shared_from_thiswhen an object needs to safely produce ashared_ptrto itself.
Follow-up 1
How is 'this' pointer used in C++?
The 'this' pointer is used in C++ to refer to the current object within a member function. It can be used to access the member variables and member functions of the class. For example, if we have a member function called 'display' in a class called 'Person', we can use the 'this' pointer to access the member variables of the current object like this:
void Person::display() {
cout << "Name: " << this->name << endl;
cout << "Age: " << this->age << endl;
}
Follow-up 2
Can you give an example of 'this' pointer usage?
Sure! Here's an example of how the 'this' pointer can be used in C++:
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int width, int height) {
this->width = width;
this->height = height;
}
int calculateArea() {
return this->width * this->height;
}
};
int main() {
Rectangle rect(5, 10);
cout << "Area: " << rect.calculateArea() << endl;
return 0;
}
Follow-up 3
What is the significance of 'this' pointer?
The 'this' pointer is significant in C++ because it allows us to differentiate between the local variables and the member variables of a class. It helps in accessing the member variables and member functions of the current object. It is especially useful when we have a local variable with the same name as a member variable, as it allows us to explicitly specify that we want to access the member variable using the 'this' pointer.
5. What is the concept of class methods in C++?
Class methods are member functions defined inside (or associated with) a class. They define the behaviour of objects and can access all members of the class, including private ones.
Types of class methods:
1. Regular (instance) member functions
Called on a specific object; have access to this:
class Counter {
public:
void increment() { ++count_; }
int value() const { return count_; }
private:
int count_ = 0;
};
Counter c;
c.increment();
2. const member functions
Declare with trailing const; promise not to modify the object. Can be called on const objects. Should be used on any method that is logically read-only:
int value() const { return count_; } // callable on const Counter
3. Static member functions
Belong to the class, not to any instance. No this pointer; can only access static members directly:
class MathUtils {
public:
static int square(int n) { return n * n; }
};
MathUtils::square(5); // called via class name, no object needed
4. Virtual member functions Enable runtime polymorphism. Derived classes override them; the correct version is selected through a vtable at runtime:
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default; // virtual destructor — required for polymorphic base
};
class Circle : public Shape {
public:
Circle(double r) : r_{r} {}
double area() const override { return 3.14159 * r_ * r_; }
private:
double r_;
};
Always mark overrides with override (C++11) so the compiler catches signature mismatches.
5. Inline member functions
Functions defined inside the class body are implicitly inline — the compiler may expand the call site. For performance-critical short functions this is desirable.
6. Special member functions
The compiler can generate: default constructor, destructor, copy constructor, copy assignment, move constructor, move assignment. Control them explicitly with = default or = delete:
class NonCopyable {
public:
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
Method definition outside the class: Large methods are typically defined outside the class body using the scope resolution operator:
// In header
class Foo {
public:
void bar();
};
// In .cpp
void Foo::bar() {
// implementation
}
Common interview follow-up: "What is the difference between a static method and a virtual method?" — Static methods are resolved at compile time and have no this; virtual methods are resolved at runtime through the vtable and require an object. They serve completely different purposes and cannot be combined (static virtual is illegal in C++).
Follow-up 1
How do you declare and define a class method?
To declare a class method in C++, you need to use the 'static' keyword before the return type in the function declaration. The function definition should also include the class name and the scope resolution operator (::). Here's an example:
class MyClass {
public:
static void myClassMethod();
};
void MyClass::myClassMethod() {
// Function body
}
Follow-up 2
Can you give an example of a class method?
Sure! Here's an example of a class method in C++:
class MathUtils {
public:
static int add(int a, int b) {
return a + b;
}
};
int main() {
int result = MathUtils::add(5, 3);
// result = 8
return 0;
}
Follow-up 3
What is the difference between a class method and a class member?
A class method in C++ is a member function that is associated with the class itself, while a class member refers to any member (variable or function) of the class. Class methods can be called without creating an object of the class, whereas class members can only be accessed through an object of the class. Additionally, class methods are declared and defined using the 'static' keyword, while class members do not require the 'static' keyword.
Live mock interview
Mock interview: Classes and Objects in C++
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.