AIOU LIBRARY • READ ONLY
AIOULIBRARY.COM • CODE 3401
AIOU LIBRARY • DO NOT COPY
Unit 4: Object-Oriented Programming Concepts in C++
Easy Chapter Introduction & Learning Objectives
Welcome to Unit 4 of Course 3401, Programming Fundamentals (C++ / Python). In the previous units, you learned how to write programs using basic control structures, loops, and functions. This style of coding is known as Procedural Programming, where you write step-by-step instructions to tell the computer what to do. However, as software programs grow larger and more complex, procedural programming becomes hard to manage, update, and debug. To solve this problem, computer scientists developed a powerful new way of thinking about coding called Object-Oriented Programming (OOP).
Object-Oriented Programming is a method of programming that uses classes and objects to represent real-world things and ideas. Imagine you are building a software system for a university like Allama Iqbal Open University (AIOU). Instead of writing thousands of lines of confusing procedural code, OOP allows you to create software models of real things—such as a Student, a Course, a Tutor, or an Assignment. Each of these real-world items has specific traits (like a registration number, name, or course code) and specific actions (like submitting an assignment, paying a fee, or grading a paper).
By the time you finish studying this comprehensive unit, you will be able to:
- Understand the fundamental differences between Procedural Programming and Object-Oriented Programming (OOP).
- Define classes and create (instantiate) objects in C++.
- Write member functions and use data hiding techniques with access specifiers (`public`, `private`, and `protected`).
- Initialize and destroy objects properly using constructors and destructors.
- Reuse existing code through the concept of inheritance and its various types.
- Achieve flexibility in your programs using polymorphism, function overloading, and virtual functions.
- Apply these concepts to solve real-world programming problems in C++ with confidence and ease.
Detailed Explanation of Every Unit Topic (With Simple Examples)
1. Introduction to Object-Oriented Programming (OOP) and Procedural vs. OOP Paradigms
Before diving into C++ code, let us understand what a programming paradigm is. A paradigm is simply a style, model, or way of thinking about how to write computer programs. Two of the most popular paradigms are Procedural Programming and Object-Oriented Programming.
- Procedural Programming: In this approach, a program is viewed as a list of instructions or procedures (functions) that manipulate data. The data and the functions that operate on that data are kept completely separate. Think of a recipe: step 1, step 2, step 3. It works well for small tasks, but as a program grows to thousands of lines, changing one small part can break the entire program because everything is tightly linked. Languages like C (traditionally) follow this approach.
- Object-Oriented Programming (OOP): In this approach, data and the functions that manipulate that data are bundled together into a single unit called an "Object." Instead of focusing on steps, OOP focuses on the "things" (objects) that make up the system and how these things interact with one another.
Real-Life Pakistani Example: Imagine managing a fleet of Daewoo buses or Pakistan Railways trains. In a procedural system, you might have separate lists of train engine numbers, passenger names, and ticket prices, with massive lists of functions to update each list independently. If a train is canceled, you have to manually update dozens of unconnected variables. In an OOP system, you create a Train class. Every individual train is an object containing its own data (train number, total seats, current location) and its own functions (book ticket, update location, check delay). This makes management clean, organized, and scalable.
The four core pillars of Object-Oriented Programming are:
- Encapsulation: Wrapping data and functions into a single unit (class) and protecting it from outside interference.
- Abstraction: Hiding complex background details and showing only the essential features to the user (like driving a car by pressing the accelerator without needing to know how fuel burns in the engine).
- Inheritance: Allowing a new class to adopt the properties and behaviors of an existing class, promoting code reuse.
- Polymorphism: Giving an action the ability to take many forms depending on the object performing it.
2. Classes and Objects: Declaration and Instantiation
At the heart of C++ Object-Oriented Programming lie two fundamental concepts: Classes and Objects. Without understanding these two, you cannot write an OOP program.
- Class: A class is a user-defined blueprint, template, or prototype from which objects are created. It does not occupy any memory by itself. Think of a class as an architect's blueprint for a house in Islamabad. The blueprint defines where the rooms, doors, and windows will be, but nobody can actually live inside a piece of paper.
- Object: An object is an instance of a class. When the builder actually constructs a physical house using that blueprint, that physical house is the "object." An object occupies actual memory in your computer's RAM and has real values for its variables.
Let us look at a simple C++ code example demonstrating how to declare a class and instantiate an object for an AIOU Student:
#include <iostream>
#include <string>
using namespace std;
// Step 1: Declaring the Class
class Student {
public:
string name;
string program;
int rollNo;
// A member function to display student details
void displayStudentInfo() {
cout << "Student Name: " << name << endl;
cout << "Program: " << program << endl;
cout << "Roll Number: " << rollNo << endl;
}
};
int main() {
// Step 2: Instantiating Objects from the Class
Student student1; // student1 is an object of class Student
// Assigning values to student1's attributes
student1.name = "Ali Ahmed";
student1.program = "BS Computer Science";
student1.rollNo = 340100;
// Calling the member function
student1.displayStudentInfo();
return 0;
}
In this example, Student is the blueprint (class), and student1 is the physical house (object) created in memory with specific values assigned to Ali Ahmed.
3. Member Functions
Member functions are functions that are declared inside a class definition. They operate on the data (variables) stored inside the object. In our previous example, displayStudentInfo() is a member function because it belongs to the Student class and has direct access to name, program, and rollNo.
In C++, you can define member functions in two ways:
- Inside the Class Definition: Written directly inside the class body (as shown in the previous example). This is best for very short functions.
- Outside the Class Definition: Declared inside the class using a prototype, but defined outside the class using the scope resolution operator (
::). This keeps your code clean and organized.
Here is how you define a member function outside the class:
#include <iostream>
using namespace std;
class Calculator {
public:
int num1, num2;
// Function prototype inside class
int addNumbers();
};
// Defining the function outside the class using scope resolution operator ::
int Calculator::addNumbers() {
return num1 + num2;
}
int main() {
Calculator calc;
calc.num1 = 15;
calc.num2 = 25;
cout << "Sum is: " << calc.addNumbers() << endl;
return 0;
}
4. Access Specifiers (Public, Private, and Protected)
One of the greatest benefits of OOP is data hiding (Encapsulation). We do not want anyone outside our class to randomly mess up our internal data. C++ uses keywords called Access Specifiers to control who can access the variables and functions inside a class. There are three access specifiers in C++:
- Public: Members declared as public can be accessed from anywhere in the program—both inside and outside the class.
- Private: Members declared as private can *only* be accessed by member functions inside the same class. Code outside the class (like in
main()) cannot touch private data directly. This protects sensitive data. - Protected: Members declared as protected are similar to private members, but they can also be accessed by child (derived) classes through inheritance. We will explore this further in the inheritance section.
Real-Life Pakistani Example: Think of your bank account with Habib Bank Limited (HBL). Your account balance and PIN code are Private data; nobody on the street can walk up to your account and change your balance. However, the ATM machine provides a Public function (like withdrawing cash or checking balance) that you can safely interact with through authorized channels.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // Private data: cannot be accessed directly from main()
public:
// Setter function to deposit money safely
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited successfully. New balance: " << balance << endl;
} else {
cout << "Invalid deposit amount!" << endl;
}
}
// Getter function to check balance safely
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
// myAccount.balance = 5000; // Error! balance is private and cannot be accessed directly.
myAccount.deposit(5000); // Correct way using public member function
cout << "Current Balance: " << myAccount.getBalance() << endl;
return 0;
}
5. Constructors and Destructors
When working with objects, you often need to initialize their values right when they are created, and clean up after them when they are destroyed. C++ provides special member functions for this exact purpose: Constructors and Destructors.
- Constructor: A constructor is a special member function that is automatically called as soon as an object of a class is created. It has the *exact same name as the class* and does not have any return type (not even
void). It is mainly used to assign initial values to object variables. - Destructor: A destructor is a special member function that is automatically called when an object goes out of scope or is deleted from memory. Its name is the class name preceded by a tilde symbol (
~). It is used to release memory or close files when the object is destroyed.
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
public:
// Constructor to initialize book details automatically
Book(string bookTitle, double bookPrice) {
title = bookTitle;
price = bookPrice;
cout << "Constructor called: Book '" << title << "' created in memory." << endl;
}
void displayBook() {
cout << "Title: " << title << ", Price: Rs. " << price << endl;
}
// Destructor to clean up when object is destroyed
~Book() {
cout << "Destructor called: Book '" << title << "' removed from memory." << endl;
}
};
int main() {
cout << "Inside main function..." << endl;
// Creating object triggers constructor
Book programmingBook("C++ Programming Fundamentals", 1250.00);
programmingBook.displayBook();
cout << "Ending main function..." << endl;
return 0; // Destructor is automatically called here when programmingBook goes out of scope
}
6. Inheritance and Types of Inheritance
One of the most powerful features of OOP is Inheritance. Inheritance allows a new class to adopt the properties (variables) and behaviors (functions) of an existing class. This prevents you from writing the same code over and over again (known as the DRY principle: Don't Repeat Yourself).
- Base Class (Parent Class): The original class whose properties are inherited.
- Derived Class (Child Class): The new class that inherits from the base class. It gets all public and protected features of the base class and can also add its own new variables and functions.
Real-Life Pakistani Example: In a university, you have a general class of people called Person who all have a name, CNIC, and phone number. Instead of writing separate code for Student, Teacher, and Staff, you can make Person the parent class. Student inherits from Person and adds student-specific features like roll number and semester. Teacher inherits from Person and adds employee-specific features like salary and department.
There are five main types of inheritance in C++:
- Single Inheritance: A single derived class inherits from a single base class (e.g.,
Doginherits fromAnimal). - Multilevel Inheritance: A class is derived from another derived class (e.g.,
Puppyinherits fromDog, which inherits fromAnimal). - Multiple Inheritance: A single derived class inherits from two or more base classes simultaneously (e.g.,
TeachingAssistantinherits from bothStudentandTeacher). - Hierarchical Inheritance: Multiple derived classes inherit from a single base class (e.g., both
CatandDoginherit fromAnimal). - Hybrid Inheritance: A combination of two or more types of inheritance (e.g., combining multiple and multilevel inheritance).
Here is a simple C++ code example showing Single Inheritance:
#include <iostream>
#include <string>
using namespace std;
// Base Class (Parent)
class Person {
public:
string name;
int age;
void introduce() {
cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;
}
};
// Derived Class (Child) inheriting from Person
class AIOUStudent : public Person {
public:
int studentID;
void study() {
cout << "I am studying my AIOU course materials online." << endl;
}
};
int main() {
AIOUStudent myStudent;
// Accessing base class variables and functions using child object
myStudent.name = "Fatima Bibi";
myStudent.age = 22;
myStudent.studentID = 998877;
myStudent.introduce(); // Inherited function
myStudent.study(); // Child's own function
return 0;
}
7. Polymorphism, Function Overloading, and Virtual Functions
The word Polymorphism comes from Greek roots: Poly means "many" and morph means "forms." In programming, polymorphism means the ability of a single function name or operator to perform different tasks depending on the context in which it is used.
There are two main types of polymorphism in C++:
- Compile-time Polymorphism (Static Binding): Achieved through Function Overloading and Operator Overloading. The compiler decides which function to run before the program even starts running.
- Run-time Polymorphism (Dynamic Binding): Achieved through Virtual Functions and pointers/references. The decision of which function to execute is made while the program is actually running.
Function Overloading (Compile-time Polymorphism)
Function overloading allows you to have multiple functions with the exact same name in the same class or program, provided that their parameter lists (number, type, or order of arguments) are different.
Real-Life Pakistani Example: Think of an online payment gateway (like EasyPaisa or JazzCash). The function name to send money might be sendPayment(). If you send money using a mobile number, the system uses sendPayment(string mobileNumber, double amount). If you send money using a bank account, the system uses sendPayment(string ibanNumber, string bankName, double amount). The function name is the same, but the computer knows which one to run based on the inputs you provide.
#include <iostream>
using namespace std;
class Printer {
public:
// Function with 1 integer parameter
void printValue(int i) {
cout << "Printing integer: " << i << endl;
}
// Overloaded function with 1 double parameter
void printValue(double d) {
cout << "Printing double: " << d << endl;
}
// Overloaded function with 2 string parameters
void printValue(string s1, string s2) {
cout << "Printing strings: " << s1 << " and " << s2 << endl;
}
};
int main() {
Printer obj;
obj.printValue(100); // Calls the int version
obj.printValue(99.99); // Calls the double version
obj.printValue("Hello", "AIOU"); // Calls the string version
return 0;
}
Virtual Functions (Run-time Polymorphism)
Sometimes, a child class wants to modify or replace a function inherited from its parent class. This is called Function Overriding. If you use pointers to manage parent and child classes, C++ by default calls the parent's function unless you use the keyword virtual.
A virtual function is a member function inside a parent class that you expect to be redefined in child classes. By marking a function as virtual, you tell C++ to look at the *actual object* in memory while running the program, rather than the pointer type, and execute the correct overridden function.
#include <iostream>
using namespace std;
// Base Class
class Animal {
public:
// Virtual function
virtual void sound() {
cout << "Animal makes a generic sound." << endl;
}
};
// Derived Class 1
class Dog : public Animal {
public:
void sound() override { // Overriding base class function
cout << "Dog barks: Woof! Woof!" << endl;
}
};
// Derived Class 2
class Cat : public Animal {
public:
void sound() override { // Overriding base class function
cout << "Cat meows: Meow! Meow!" << endl;
}
};
int main() {
Animal *animalPtr; // Base class pointer
Dog myDog;
Cat myCat;
animalPtr = &myDog;
animalPtr->sound(); // Output will be Dog barks due to virtual function!
animalPtr = &myCat;
animalPtr->sound(); // Output will be Cat meows!
return 0;
}
Key Terms & Easy Glossary
- Object-Oriented Programming (OOP): A programming paradigm based on the concept of "objects," which bundle data (attributes) and methods (functions) together. It models real-world entities to make code modular, reusable, and easy to maintain.
- Class: A user-defined blueprint or template used to create objects. It defines the variables and member functions that all objects of that type will possess.
- Object: An instance of a class that exists physically in computer memory (RAM). Each object has its own unique set of values for the attributes defined in its class.
- Procedural Programming: A programming style based upon the concept of procedure calls (routines, subroutines, or functions), where instructions are executed step-by-step in a linear sequence.
- Encapsulation: The mechanism of wrapping data (variables) and code acting on the data (methods) together as a single unit, while restricting direct access to some of the object's components to protect data integrity.
- Access Specifiers: Keywords in C++ (`public`, `private`, and `protected`) that determine the scope and visibility of class members to outside code and derived classes.
- Constructor: A special member function of a class that is automatically executed whenever a new object of that class is created. It is primarily used to initialize object variables with default or custom values.
- Destructor: A special member function with a tilde symbol (
~) prefixed to the class name, which is automatically invoked when an object goes out of scope or is deleted, freeing up system resources. - Inheritance: An OOP feature that enables a child class to inherit attributes and methods from a parent class, promoting code reuse and establishing a hierarchical relationship between classes.
- Polymorphism: The ability of a programming language to process objects differently depending on their data type or class, allowing a single function name or operator to perform various tasks.
- Function Overloading: A compile-time polymorphism feature where multiple functions share the exact same name within the same scope but differ in the number, type, or sequence of their parameters.
- Virtual Function: A member function declared within a base class using the `virtual` keyword and overridden in a derived class, enabling dynamic binding and run-time polymorphism through pointers or references.
Q: What is the fundamental difference between procedural programming and object-oriented programming?
Easy Answer:
Procedural programming and object-oriented programming (OOP) are two completely different paradigms (approaches) used by programmers to design and write software. The fundamental difference lies in how they organize and process data.
* Focus and Approach:
* Procedural Programming: Focuses on procedures or functions (step-by-step instructions). It treats data and the functions that manipulate that data as two separate entities. Languages like C use this approach.
* Object-Oriented Programming (OOP): Focuses on objects that combine both data (attributes) and functions (behaviors) into a single unit. Languages like C++ and Python use this approach.
* Data Security and Access:
* Procedural: Data is usually global or passed freely between functions, making it easier for any part of the program to accidentally modify data, leading to bugs.
* OOP: Data is kept safe inside objects using encapsulation and access specifiers, meaning it can only be modified through controlled member functions.
* Reusability and Extensibility:
* Procedural: Code reuse is difficult; adding new features often requires rewriting existing logic.
* OOP: Supports inheritance and polymorphism, making it very easy to reuse existing code and extend systems without altering tested codebases.
* Real-World Modeling:
* Procedural: Difficult to map real-world entities directly to functions.
* OOP: Excellent for modeling real-world entities (e.g., a Bank Account, a Car, a Student) because everything is represented as a distinct object with properties and actions.
Example Comparison:
In procedural C, you would have a global array of employee salaries and a separate function calculateTax(salary). In OOP C++, you would have an Employee class containing both the salary variable and a calculateTax() member function inside the class itself.
Q: Define a class named 'Student' with data members for roll number and name, and member functions to input and display data.
Easy Answer:
A class in C++ acts as a blueprint or template for creating objects. Below is the complete, easy-to-understand C++ code defining a Student class along with its data members and member functions, accompanied by a main() function to demonstrate its usage.
* Data Members: Variables declared inside the class to hold state (int rollNo and string name).
* Member Functions: Functions declared inside the class to operate on data (inputData() and displayData()).
* Access Specifier: The public: keyword ensures that these functions can be accessed from outside the class (such as from main()).
```cpp
#include s1 encapsulates both the student's personal information and the procedures needed to input and display that information.
Q: Explain the role and significance of access specifiers (private, public, protected) in C++ classes.
Easy Answer:
Access specifiers are keywords used in C++ classes to implement encapsulation and control the visibility and accessibility of class members (variables and functions) from outside the class. They act as security guards for your data.
* 1. Private:
* Access Level: Members declared as private can only be accessed by member functions inside the same class. They cannot be accessed or viewed by outside functions or objects.
* Significance: Provides maximum data security, shielding critical data from unauthorized external modification (Data Hiding). By default, members of a class in C++ are private.
* 2. Public:
* Access Level: Members declared as public can be accessed from anywhere in the program—both inside and outside the class, including by object instances in main().
* Significance: Used for interface functions (like getters and setters or input/display methods) that allow safe interaction with the private data of the class.
* 3. Protected:
* Access Level: Members declared as protected are similar to private members, but with one major exception: they can be accessed by member functions of derived (child) classes through inheritance.
* Significance: Essential when designing class hierarchies where child classes need direct access to parent class variables without exposing those variables to the outside world.
Code Demonstration:
```cpp
class Demo {
private:
int secretCode; // Only accessible inside Demo
public:
int publicId; // Accessible everywhere
protected:
int familyData; // Accessible in Demo and child classes
};
```
Q: What is a constructor? How does a default constructor differ from a parameterized constructor?
Easy Answer:
A constructor is a special member function of a class that is automatically executed (called) whenever an object of that class is created.
* It has the exact same name as the class itself.
* It does not have any return type (not even void).
* Its primary purpose is to initialize the data members of an object.
The two primary types of constructors are the default constructor and the parameterized constructor:
* Default Constructor:
* It takes no arguments (parameters).
* If you do not write any constructor in your class, the C++ compiler automatically provides a default constructor behind the scenes.
* It initializes data members with default garbage values or zero.
* Parameterized Constructor:
* It accepts one or more arguments passed during object creation.
* It allows the programmer to pass custom initial values to the object's data members right at the time of creation.
* It must be explicitly defined by the programmer.
Code Example Comparing Both:
```cpp
#include
Q: Write a C++ program to demonstrate single inheritance using a base class 'Vehicle' and a derived class 'Car'.
Easy Answer:
Inheritance is an object-oriented programming feature that allows a new class (derived/child class) to inherit properties and behaviors (data members and member functions) from an existing class (base/parent class). Single inheritance occurs when a class is derived from one base class only.
Below is a complete C++ program demonstrating single inheritance:
```cpp
#include Car class inherits brand and speed from Vehicle, adding its own unique seatingCapacity property.
Q: Explain the concept of function overloading with a suitable code example.
Easy Answer:
Function Overloading is a feature of Object-Oriented Programming (part of compile-time polymorphism) that allows you to create multiple functions with the exact same name in the same scope, provided their parameter lists are different.
* How it works: The compiler distinguishes between the overloaded functions by looking at the number, type, or order of arguments passed during the function call.
* Rule: Changing only the return type of a function is not sufficient for function overloading; the parameters must differ.
* Benefit: It improves code readability by eliminating the need to invent different names for essentially the same operation performed on different data types (e.g., having separate functions for adding integers, floats, etc.).
Code Example:
```cpp
#include
Q: Define Object-Oriented Programming.
Easy Answer: Object-Oriented Programming (OOP) is a programming paradigm or methodology that relies on the concept of classes and objects. It is designed to model real-world entities into software components to create reusable, modular, and maintainable code. Instead of focusing purely on functions and procedures (as in procedural programming), OOP bundles together data (attributes) and the functions that manipulate that data (methods) inside single units called objects. The four major pillars that define OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.
Q: What is an object in C++?
Easy Answer: An object is a basic building block of Object-Oriented Programming and represents a real-world entity in a program. In technical terms, an object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Once instantiated, the object occupies physical memory in RAM and contains its own unique set of data values corresponding to the class's variables, alongside access to the class's member functions.
Q: Differentiate between a class and an object.
Easy Answer: The key differences between a class and an object are: * Definition: A class is a user-defined blueprint or template, whereas an object is an instance of that class. * Memory Allocation: A class does not consume memory when declared. An object consumes memory when it is instantiated in RAM. * Creation Count: You can create only one class definition, but you can create as many objects from that single class as needed. * Analogy: A class is like an architectural blueprint for a house, while an object is the actual physical house built from that blueprint.
Q: What is the purpose of a destructor?
Easy Answer:
A destructor is a special member function of a class that is automatically executed when an object goes out of scope or is deleted from memory.
* Naming: It has the same name as the class, preceded by a tilde (~) sign (e.g., ~Student()).
* Purpose: Its primary purpose is to release dynamic memory, close open files, and free up system resources acquired by the object during its lifecycle, thus preventing memory leaks.
Q: Can a constructor be overloaded? Justify.
Easy Answer: Yes, a constructor can be overloaded. Constructor overloading occurs when a class has multiple constructors with the same name (the class name) but different parameter lists (different number, type, or order of arguments). This is fully justified and extremely useful because it allows a programmer to initialize objects in different ways—for example, creating an object with default values using a default constructor, or initializing it with specific custom values using a parameterized constructor.
Q: What is meant by inheritance?
Easy Answer: Inheritance is an OOP feature that allows a new class (called a derived or child class) to acquire the properties and behaviors (data members and member functions) of an existing class (called a base or parent class). The main significance of inheritance is code reusability. Instead of rewriting the same code from scratch, child classes inherit tested features and can also add their own unique features or override inherited behaviors.
Q: Define polymorphism in your own words.
Easy Answer:
Polymorphism literally means "many forms." In C++, polymorphism allows the same entity (such as a function, operator, or pointer) to behave differently in different contexts. For example, a single function name draw() can be used to draw a circle, a rectangle, or a triangle, with the program automatically figuring out which specific version to execute. It is broadly divided into compile-time polymorphism (function/operator overloading) and run-time polymorphism (virtual functions/overriding).
Q: What is a virtual function?
Easy Answer:
A virtual function is a member function declared in a base class using the virtual keyword and overridden in a derived class. Its purpose is to achieve run-time polymorphism (dynamic binding). When you point a base class pointer to a derived class object and call a virtual function, C++ ensures that the correct derived-class version of the function is executed at runtime rather than the base-class version.
Q: What is the scope resolution operator (::) used for in classes?
Easy Answer:
The scope resolution operator (::) is used in C++ to identify and access the context where a particular identifier belongs. In the context of classes, it is primarily used to define member functions outside the class body. It connects a function name to its parent class, telling the compiler which class the function belongs to (e.g., void Student::displayData() { ... }). It is also used to access global variables or static members shadowed by local variables.
Q: State the significance of encapsulation.
Easy Answer: Encapsulation is the mechanism of wrapping data (variables) and code acting on the data (methods) together as a single unit (a class) and restricting direct access to some of the object's components. * Significance: Its greatest significance is data hiding and security. By making data private and providing controlled public getter/setter functions, it prevents unauthorized external code from corrupting state, while hiding internal implementation details from the outside world.
Long Question: Discuss the four major pillars of Object-Oriented Programming in detail with appropriate C++ code examples for each.
Object-Oriented Programming (OOP) is a powerful programming paradigm that uses classes and objects to model real-world entities, making code reusable, modular, and maintainable. Unlike procedural programming which focuses on step-by-step functions, OOP centers around data and the operations that can be performed on that data. In C++, OOP is built upon four foundational pillars: Encapsulation, Abstraction, Inheritance, and Polymorphism. Mastery of these four pillars is essential for designing robust enterprise-grade applications. This comprehensive guide explores each of these pillars in detail, supported by clear, exam-standard C++ code examples and everyday analogies.
1. Introduction to Object-Oriented Programming (OOP)
OOP shifts the focus from writing pure procedural instructions to creating software components that mirror real-world objects. An 'object' is an instance of a 'class', possessing both state (represented by variables or attributes) and behavior (represented by functions or methods). The four pillars act as design principles that enforce clean code boundaries, secure data handling, and code extensibility.
2. Pillar 1: Encapsulation (Data Hiding and Bundling)
Encapsulation is the mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In C++, this is achieved by creating a class and using access specifiers (`private`, `protected`, `public`) to restrict direct outside access to sensitive internal states. Think of a capsule containing medicine; you swallow the capsule without needing to know the chemical composition inside. Similarly, an object exposes a safe public interface while hiding its fragile implementation details.
3. Implementation of Encapsulation in C++
To implement encapsulation, data members are declared as `private`, preventing direct modification from outside functions. Controlled access is provided via `public` getter and setter member functions. This allows the class to validate data before updating it. For example, a student age cannot be set to a negative value. Encapsulation ensures internal data integrity and reduces system-wide coupling.
4. C++ Code Example Demonstrating Encapsulation
#include <iostream>
using namespace std;
class Employee {
private:
double salary; // Private data hidden from outside
public:
// Setter function with validation
void setSalary(double s) {
if (s >= 0) {
salary = s;
} else {
cout << "Invalid salary!" << endl;
}
}
// Getter function to retrieve data safely
double getSalary() {
return salary;
}
};
int main() {
Employee emp;
emp.setSalary(50000.0); // Safe access via setter
cout << "Employee Salary: " << emp.getSalary() << endl;
return 0;
}
5. Pillar 2: Abstraction (Hiding Complexity)
Abstraction is the concept of exposing only the essential features of an object while hiding the complex background implementation details. Consider driving a car: you press the accelerator to move forward, without needing to understand fuel injection, combustion chambers, or piston movement. In C++, abstraction is implemented using abstract classes and pure virtual functions.
6. Implementation of Abstraction via Abstract Classes
An abstract class contains at least one pure virtual function (a function declared with `= 0`). It cannot be instantiated directly; instead, it serves as a blueprint for derived classes. By forcing subclasses to implement the pure virtual functions, abstraction establishes a uniform interface across different underlying implementations, promoting design consistency.
7. C++ Code Example Demonstrating Abstraction
#include <iostream>
using namespace std;
// Abstract class
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle..." << endl;
}
};
int main() {
Shape* s = new Circle(); // Polymorphic pointer
s->draw(); // Hides complexity of drawing mechanics
delete s;
return 0;
}
8. Pillar 3: Inheritance (Code Reusability and Hierarchy)
Inheritance is a mechanism where a new class (derived or child class) adopts the properties and behaviors of an existing class (base or parent class). This models an "IS-A" relationship (e.g., a Manager "IS-A" Employee). Inheritance eliminates code redundancy, allowing developers to write base functionality once and extend or specialize it in child classes without rewriting code.
9. Types and Benefits of Inheritance
C++ supports single, multiple, multilevel, hierarchical, and hybrid inheritance. The primary benefits include code reusability, logical categorization, and extensibility. Access specifiers (`public`, `protected`, `private`) determine how base class members are inherited. Protected members remain accessible within derived classes while staying hidden from outside code.
10. C++ Code Example Demonstrating Inheritance
#include <iostream>
#include <string>
using namespace std;
class Animal { // Base Class
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
class Dog : public Animal { // Derived Class
public:
void bark() {
cout << "The dog barks: Woof! Woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // Inherited behavior
myDog.bark(); // Derived behavior
return 0;
}
11. Pillar 4: Polymorphism (Many Forms)
Polymorphism means "having many forms." In object-oriented programming, it allows a single interface to represent different underlying data types or behaviors. For instance, a `speak()` function can produce a "Bark" when called on a Dog object, and a "Meow" when called on a Cat object. Polymorphism allows flexible, extensible code where new types can be added without altering existing control structures.
12. Compile-Time vs. Run-Time Polymorphism
Polymorphism in C++ is categorized into two types:
- Compile-time (Static) Polymorphism: Achieved through function overloading and operator overloading, where the compiler resolves the function call before execution.
- Run-time (Dynamic) Polymorphism: Achieved through virtual functions and base class pointers/references, where the correct function is resolved dynamically during program execution.
13. C++ Code Example Demonstrating Run-Time Polymorphism
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show function." << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class show function." << endl;
}
};
int main() {
Base* b;
Derived d;
b = &d;
b->show(); // Outputs Derived class function due to virtual keyword
return 0;
}
14. Exam Summary & Conclusion
The four pillars of OOP—Encapsulation, Abstraction, Inheritance, and Polymorphism—form the bedrock of C++ software engineering. Encapsulation protects data integrity, abstraction simplifies complex subsystems, inheritance promotes code reuse through hierarchical design, and polymorphism enables flexible, dynamic behavior. When combined, these pillars allow programmers to build scalable, secure, and maintainable software systems that mirror real-world domains efficiently.
Long Question: Write a complete C++ program implementing a class 'BankAccount' with constructors, member functions for deposit and withdrawal, and display mechanisms, including proper encapsulation.
Designing a robust banking application requires strict adherence to Object-Oriented Programming principles, especially encapsulation and data security. A bank account must protect sensitive financial metrics—such as account balance and account number—from unauthorized external modification while providing a controlled, user-friendly interface for transactions like deposits and withdrawals. This question requires writing a complete, compile-ready C++ program that implements a `BankAccount` class complete with default/parameterized constructors, validation checks for deposits and withdrawals, display functions, and thorough encapsulation.
1. Introduction to the BankAccount Class Design
The `BankAccount` class models a real-world bank account. It contains private attributes for the account holder's name, account number, and current balance. Because financial data is highly sensitive, exposing these variables directly would compromise security. Therefore, we utilize encapsulation: private variables are managed exclusively through public member functions (`deposit`, `withdraw`, `displayAccountInfo`) equipped with rigorous logical validation.
2. Role of Constructors in BankAccount
Constructors are special member functions automatically invoked when an object of a class is created. For our `BankAccount` class, we implement two constructors:
- Default Constructor: Initializes string fields to empty/default values and balance to zero.
- Parameterized Constructor: Allows immediate initialization of account holder name, account number, and opening balance upon object instantiation.
3. Encapsulation Mechanism in Financial Software
In financial programming, data integrity is paramount. Encapsulation ensures that an account balance can never be set directly to an arbitrary value from outside the class. All modifications to the balance must pass through transaction functions (`deposit()` and `withdraw()`), which verify that deposit amounts are positive and withdrawal amounts do not exceed the available balance plus any permitted overdraft limit.
4. Deposit Member Function Implementation
The deposit function accepts a monetary amount as an argument. Before updating the balance, it checks if the amount is greater than zero. If the deposit is valid, it adds the amount to the current balance and prints a success message showing the updated balance. If a negative or zero amount is passed, it rejects the transaction with an error notification.
5. Withdrawal Member Function Implementation
The withdrawal function handles requests to subtract funds from the account. It executes two crucial checks: first, it ensures the requested withdrawal amount is positive; second, it checks whether sufficient funds exist in the account (`amount <= balance`). If funds are insufficient, the transaction is declined to prevent negative balances (unless an overdraft facility is implemented).
6. Display Mechanism and Account Summary
A display function provides a clean, formatted report of the account's current state. It outputs the account holder's name, masked or clear account number, and the current balance formatted to two decimal places. This decouples formatting logic from transaction logic, making the code easier to maintain and test.
7. Complete C++ Program Implementation
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class BankAccount {
private:
string depositorName;
string accountNumber;
double balance;
public:
// 1. Default Constructor
BankAccount() {
depositorName = "Unknown";
accountNumber = "0000000000";
balance = 0.0;
}
// 2. Parameterized Constructor
BankAccount(string name, string accNum, double initialBalance) {
depositorName = name;
accountNumber = accNum;
if (initialBalance >= 0.0) {
balance = initialBalance;
} else {
balance = 0.0;
cout << "Initial balance invalid. Set to 0.0\n";
}
}
// 3. Deposit Function
void deposit(double amount) {
if (amount > 0.0) {
balance += amount;
cout << "Successfully deposited: PKR " << fixed << setprecision(2) << amount << endl;
} else {
cout << "Error: Deposit amount must be greater than zero!\n";
}
}
// 4. Withdrawal Function
void withdraw(double amount) {
if (amount <= 0.0) {
cout << "Error: Withdrawal amount must be greater than zero!\n";
} else if (amount > balance) {
cout << "Error: Insufficient funds! Current Balance: PKR " << balance << endl;
} else {
balance -= amount;
cout << "Successfully withdrew: PKR " << fixed << setprecision(2) << amount << endl;
}
}
// 5. Display Account Details
void displayAccountInfo() const {
cout << "\n--- Bank Account Summary ---" << endl;
cout << "Account Holder : " << depositorName << endl;
cout << "Account Number : " << accountNumber << endl;
cout << "Current Balance: PKR " << fixed << setprecision(2) << balance << endl;
cout << "----------------------------\n" << endl;
}
};
// Main Driver Function
int main() {
// Creating an object using Parameterized Constructor
BankAccount myAccount("Ali Ahmed", "PK99HABB000123456789", 25000.50);
// Display initial state
myAccount.displayAccountInfo();
// Perform valid deposit
myAccount.deposit(10000.00);
// Perform invalid deposit
myAccount.deposit(-500.00);
// Perform valid withdrawal
myAccount.withdraw(7500.25);
// Perform invalid withdrawal (insufficient funds)
myAccount.withdraw(50000.00);
// Display final state
myAccount.displayAccountInfo();
return 0;
}
8. Detailed Explanation of Program Execution Flow
When the program runs, the `main()` function instantiates `myAccount` with the name "Ali Ahmed", account number "PK99HABB000123456789", and a starting balance of PKR 25,000.50. The parameterized constructor validates and sets these values securely. Subsequent calls to `deposit()` and `withdraw()` test both successful transactions and error-handling conditions (such as negative inputs or overdraft attempts). Finally, `displayAccountInfo()` outputs the accurate, updated financial standing.
9. Importance of Access Specifiers in this Program
The keyword `private` ensures that external functions or malicious code cannot execute statements like `myAccount.balance = 1000000.0;`. Only authorized methods belonging to the `BankAccount` class can alter the balance variable. This showcases true encapsulation, protecting the internal state of the object.
10. Use of `const` Correctness in Display Functions
Notice that `displayAccountInfo() const` is marked with the `const` keyword. This guarantees to the compiler—and to other programmers—that this member function will not modify any data members of the class. It is a best practice in C++ programming for read-only member functions.
11. Error Handling and Defensive Programming
Defensive programming is evident in our checks for negative deposits, zero-value withdrawals, and withdrawals exceeding the account balance. These checks prevent logical corruption of financial records and ensure the application remains stable under incorrect user inputs.
12. Exam Summary & Conclusion
This implementation of the `BankAccount` class demonstrates essential Object-Oriented programming concepts in C++. By combining private data members, public transactional methods, proper constructors, and rigorous input validation, we achieve secure encapsulation. This structure mirrors real-world banking software architecture, ensuring modularity, security, and high maintainability.
Long Question: Explain different types of inheritance supported in C++ (Single, Multiple, Multilevel, Hierarchical, and Hybrid) with diagrams and code snippets.
Inheritance is one of the core pillars of Object-Oriented Programming (OOP) in C++. It allows a new class (derived or child class) to inherit attributes and member functions from an existing class (base or parent class). This mechanism promotes code reusability, establishes logical hierarchies, and reduces code redundancy. C++ is a versatile language that supports multiple forms of inheritance, enabling developers to model complex real-world relationships. This comprehensive guide details the five primary types of inheritance supported in C++: Single, Multiple, Multilevel, Hierarchical, and Hybrid inheritance, accompanied by structural diagrams and clear code snippets.
1. Introduction to Inheritance in C++
Inheritance represents an "IS-A" relationship between classes. For example, a `Car` is a type of `Vehicle`. When designing software, inheritance allows common attributes (like `speed` and `fuelCapacity`) to be defined once in a base class and shared across multiple specialized child classes. C++ controls access to inherited members using access specifiers (`public`, `protected`, and `private`).
2. Single Inheritance
In Single Inheritance, a single derived class inherits from only one base class. This is the simplest and most common form of inheritance. It creates a straightforward parent-child hierarchy.
Diagram Structure:[Base Class] <--- [Derived Class]
C++ Code Snippet:
#include <iostream>
using namespace std;
class Vehicle { // Base Class
public:
void start() { cout << "Vehicle started." << endl; }
};
class Car : public Vehicle { // Derived Class
public:
void drive() { cout << "Car is driving." << endl; }
};
int main() {
Car myCar;
myCar.start(); // Inherited from Vehicle
myCar.drive(); // Defined in Car
return 0;
}
3. Multiple Inheritance
In Multiple Inheritance, a single derived class inherits from two or more base classes. This allows a child class to combine features from multiple distinct domains. However, it can lead to the famous "Diamond Problem" if base classes share common ancestry.
Diagram Structure:[Base 1] [Base 2] \ / [Derived Class]
C++ Code Snippet:
#include <iostream>
using namespace std;
class Engine {
public:
void startEngine() { cout << "Engine running." << endl; }
};
class MusicSystem {
public:
void playMusic() { cout << "Playing music." << endl; }
};
class SmartCar : public Engine, public MusicSystem { // Multiple Inheritance
public:
void driveSmart() { cout << "SmartCar driving autonomously." << endl; }
};
int main() {
SmartCar sc;
sc.startEngine();
sc.playMusic();
sc.driveSmart();
return 0;
}
4. Multilevel Inheritance
In Multilevel Inheritance, a derived class is created from another derived class, forming a chain or generational hierarchy (Grandparent -> Parent -> Child). Each derived class inherits the cumulative traits of all its predecessors.
Diagram Structure:[Base Class] <--- [Intermediate Derived] <--- [Final Derived]
C++ Code Snippet:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Mammal : public Animal {
public:
void walk() { cout << "Walking..." << endl; }
};
class Dog : public Mammal {
public:
void bark() { cout << "Barking: Woof!" << endl; }
};
int main() {
Dog d;
d.eat(); // From Animal
d.walk(); // From Mammal
d.bark(); // From Dog
return 0;
}
5. Hierarchical Inheritance
In Hierarchical Inheritance, multiple derived classes inherit from a single base class. This models scenarios where one general category branches out into several specialized categories (e.g., Vehicle branches into Car, Bike, and Truck).
Diagram Structure: [Base Class] / | \ [Derived 1] [Derived 2] [Derived 3]
C++ Code Snippet:
#include <iostream>
using namespace std;
class Shape {
public:
void render() { cout << "Rendering shape..." << endl; }
};
class Circle : public Shape {
public:
void drawCircle() { cout << "Drawing Circle." << endl; }
};
class Rectangle : public Shape {
public:
void drawRectangle() { cout << "Drawing Rectangle." << endl; }
};
int main() {
Circle c;
Rectangle r;
c.render(); c.drawCircle();
r.render(); r.drawRectangle();
return 0;
}
6. Hybrid Inheritance and the Diamond Problem
Hybrid Inheritance is a combination of two or more types of inheritance (e.g., combining Multilevel and Multiple inheritance). A classic structural issue in hybrid inheritance is the Diamond Problem, where a child inherits two copies of the same base class via different paths, causing ambiguity.
Diagram Structure (Diamond): [Base Class] / \[Derived 1] [Derived 2] \ / [Final Derived]
7. Resolving the Diamond Problem Using Virtual Inheritance
C++ solves the Diamond Problem using the `virtual` keyword during inheritance. By declaring intermediate inheritance as virtual, C++ ensures that only a single instance of the base class is shared across the inheritance hierarchy, eliminating ambiguity.
C++ Code Snippet (Virtual Inheritance):
#include <iostream>
using namespace std;
class Person {
public:
int id;
void displayID() { cout << "ID: " << id << endl; }
};
class Student : virtual public Person { };
class Employee : virtual public Person { };
class TeachingAssistant : public Student, public Employee { };
int main() {
TeachingAssistant ta;
ta.id = 101; // No ambiguity thanks to virtual inheritance
ta.displayID();
return 0;
}
8. Public, Protected, and Private Inheritance Modes
Inheritance visibility in C++ is governed by access specifiers:
- Public Inheritance: Public members of base become public in derived; protected remain protected.
- Protected Inheritance: Public and protected members of base become protected in derived.
- Private Inheritance: Public and protected members of base become private in derived.
9. Constructor Execution Order in Inheritance
When an object of a derived class is created, constructors execute in a specific sequence: base class constructors run first, followed by derived class constructors. Conversely, destructors execute in reverse order (derived destructor first, then base destructor).
10. Common Pitfalls in Inheritance Design
Developers must avoid overly deep inheritance hierarchies, which make code difficult to debug and maintain. The principle of composition ("has-a" relationship) should often be preferred over inheritance ("is-a" relationship) if code sharing can be achieved without tight coupling.
11. Real-World Applications of Inheritance
Inheritance is widely used in GUI frameworks (e.g., `Button` and `TextField` inheriting from a base `UIComponent` class), game development (e.g., `Player` and `Enemy` inheriting from a base `GameObject` class), and enterprise software architecture.
12. Exam Summary & Conclusion
Inheritance is a powerful pillar of Object-Oriented Programming in C++. Understanding Single, Multiple, Multilevel, Hierarchical, and Hybrid inheritance—along with handling the Diamond Problem via virtual inheritance—allows programmers to design clean, modular, and extensible class hierarchies. Proper use of inheritance reduces redundancy and models complex domain logic effectively.
Long Question: What is polymorphism? Differentiate clearly between compile-time polymorphism (function overloading) and run-time polymorphism (virtual functions) using comprehensive code examples.
Polymorphism is one of the most powerful and fundamental pillars of Object-Oriented Programming (OOP). Derived from Greek words meaning "many forms," polymorphism allows a single interface, function name, or operator to behave differently depending on the context or data types involved. In C++, polymorphism enhances code flexibility, reusability, and readability, enabling developers to write generic code that interacts with objects of various types uniformly. This comprehensive answer defines polymorphism and provides a clear, structured comparison—supported by detailed code examples—between its two primary forms: Compile-Time Polymorphism and Run-Time Polymorphism.
1. Comprehensive Definition of Polymorphism
Polymorphism is the ability of a programming language to process objects differently depending on their data type or class. In practical terms, it allows you to invoke methods on objects without needing to know their exact run-time type beforehand. C++ implements polymorphism across two major phases of execution: compile-time (static) and run-time (dynamic).
2. Overview of Compile-Time Polymorphism
Compile-time polymorphism—also known as static or early binding—is resolved by the C++ compiler during the compilation phase. Because the compiler determines which exact function or operator to call before the program runs, execution is extremely fast. Compile-time polymorphism is achieved primarily through:
- Function Overloading
- Operator Overloading
3. Function Overloading as Compile-Time Polymorphism
Function overloading allows multiple functions to share the exact same name as long as their parameter signatures differ (in terms of the number, type, or order of parameters). The compiler differentiates between them by examining the arguments passed during the function call. This provides a clean interface for operations that perform similar tasks across different data types.
4. C++ Code Example: Compile-Time Polymorphism (Function Overloading)
#include <iostream>
using namespace std;
class Calculator {
public:
// Overloaded function 1: adds two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function 2: adds three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded function 3: adds two floating-point numbers
double add(double a, double b) {
return a + b;
}
};
int main() {
Calculator calc;
cout << "Sum of 2 integers (10, 20) : " << calc.add(10, 20) << endl;
cout << "Sum of 3 integers (5, 10, 15) : " << calc.add(5, 10, 15) << endl;
cout << "Sum of 2 doubles (5.5, 4.2) : " << calc.add(5.5, 4.2) << endl;
return 0;
}
5. Overview of Run-Time Polymorphism
Run-time polymorphism—also known as dynamic or late binding—is resolved while the program is executing. It allows a base class pointer or reference to call overridden member functions of derived classes. This is essential for handling collections of mixed object types through a uniform interface. Run-time polymorphism in C++ is achieved using virtual functions and inheritance.
6. Role of Virtual Functions and the `override` Keyword
A virtual function is a member function declared in a base class using the `virtual` keyword and overridden in one or more derived classes. When a base class pointer points to a derived object and calls a virtual function, C++ uses a vtable (virtual table) mechanism to look up and execute the derived class's version of the function at run time. Using the `override` specifier ensures compile-time safety by verifying that the function correctly overrides a base class virtual function.
7. C++ Code Example: Run-Time Polymorphism (Virtual Functions)
#include <iostream>
using namespace std;
class Animal {
public:
// Virtual function enables run-time polymorphism
virtual void sound() {
cout << "Some generic animal sound..." << endl;
}
virtual ~Animal() {} // Virtual destructor for safe cleanup
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks: Woof! Woof!" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows: Meow! Meow!" << endl;
}
};
int main() {
Animal* ptr1 = new Dog();
Animal* ptr2 = new Cat();
// Dynamic binding occurs at run-time based on actual object type
ptr1->sound(); // Outputs Dog's sound
ptr2->sound(); // Outputs Cat's sound
delete ptr1;
delete ptr2;
return 0;
}
8. Detailed Comparison: Compile-Time vs. Run-Time Polymorphism
| Feature | Compile-Time Polymorphism | Run-Time Polymorphism |
|---|---|---|
| Binding Time | Resolved during compilation (Early Binding) | Resolved during execution (Late Binding) |
| Mechanism | Function Overloading & Operator Overloading | Virtual Functions & Base Pointers/References |
| Performance | Faster execution (no run-time lookup overhead) | Slight overhead due to vtable pointer lookups |
| Flexibility | Less flexible; exact signatures must match at compile time | Highly flexible; handles unknown object types dynamically |
9. Understanding the Vtable (Virtual Table) Mechanism
Under the hood, C++ implements run-time polymorphism using a Virtual Table (vtable) and a Virtual Pointer (vptr). Every class with virtual functions has a vtable containing function pointers. Every object of that class contains a vptr pointing to the vtable. When a virtual function is called through a pointer, the vptr looks up the correct function address in the vtable at run time.
10. Common Pitfalls and Best Practices
When working with run-time polymorphism, always declare a virtual destructor in your base class. If you delete a derived object through a base class pointer without a virtual destructor, the derived class's destructor will not be called, resulting in memory leaks. Compile-time polymorphism, on the other hand, should be used when behavior is known beforehand and maximum execution speed is required.
11. Real-World Use Cases for Polymorphism
Polymorphism is used extensively in game engines (managing various types of enemies or rendering items through a generic `GameObject` pointer), graphic applications (drawing shapes like circles, rectangles, and triangles via a common `Shape` interface), and database drivers supporting multiple database backends.
12. Exam Summary & Conclusion
Polymorphism provides flexibility and extensibility in C++ object-oriented programming. Compile-time polymorphism (function overloading) offers fast, static resolution during compilation, while run-time polymorphism (virtual functions) enables dynamic, flexible behavior resolution during execution. Mastering both forms allows developers to build efficient, scalable, and maintainable software systems.
MCQ #1 Which programming paradigm focuses primarily on procedures or functions rather than data?
MCQ #2 What is the blueprint or user-defined data type from which objects are created?
MCQ #3 Which access specifier makes class members accessible from outside the class?
MCQ #4 By default, members of a class in C++ are:
MCQ #5 Which special member function is automatically called when an object is created?
MCQ #6 What is the symbol used to declare a destructor in C++?
MCQ #7 What is the mechanism of deriving a new class from an existing class called?
MCQ #8 Which type of inheritance involves a class deriving from more than one base class?
MCQ #9 What does the term 'Polymorphism' literally mean?
MCQ #10 Which concept allows multiple functions to have the same name with different parameters?
MCQ #11 Which keyword is used in C++ to declare a virtual function?
MCQ #12 Which access specifier restricts member access to the class itself and its derived classes?
MCQ #13 What is an instance of a class called?
MCQ #14 Which OOP principle hides the internal representation and details of an object?
MCQ #15 When is a destructor automatically called in C++?