Unit 1 (Programming in c++)
Unit 1 (Programming in c++)
C++ Fundamentals
C++ character set
The term "C++ character set" refers to the characters and symbols that the C++ program can comprehend and
accept. The character set basically consists of combining some mathematical symbols, such as the Digits and Special
symbols, with the Alphabets and White Spaces of the English language.
Identifiers- Identifiers are the unique names given to variables, classes, functions, or other entities by the
programmer.
Example: int money, char name[50] => Here money and name are Identifiers.
Data Types
int:
The integer datatype in C is used to store the integer numbers.
Size: Typically, 4 bytes (depends on the system).
float:
It is used to store decimal numbers with single precision. Can have max 7 numbers after decimal point
Size: Typically, 4 bytes.
char:
Character data type allows its variable to store only a single character.
Size: Typically, 1 byte.
double:
It is used to store decimal numbers with double precision. Can have 14 numbers after a decimal point.
Size: Typically, 8 bytes.
void:
It does not provide a result value to its caller. It is used to represent nothing.
Qualifiers
short:
Used for small integers.
Size: Typically, 2 bytes (but this can vary by system).
Example: short num = 10;
long:
Used for large integers.
Size: Typically, 4 bytes for long and 8 bytes for long long on most systems.
Example: long distance = 1000000000;
signed:
Can only store both positive and negative integers. Used for integers
Size: 4 bytes
Example: signed int balance = -100;
unsigned:
Can only store positive integers.
Size: 4 bytes
Example: unsigned int count = 50;
const:
Specifies that a variable’s value cannot be changed after it is initialized. It makes the value constant during the
program’s execution.
Example: const int maxLimit = 100;
Constants
Integer Constants:
Integer constants are whole numbers (both positive and negative) without any decimal points.
Example: const int x = 100; // 100 is an integer constant
Character Constants:
Represent single characters enclosed in single quotes (' ').
Example: const char letter = 'A’; // 'A' is a character constant
String Constants:
These are sequences of characters enclosed in double quotes (" ").
Example: const char greeting[] = "Hello, World!"; // String constant
Example: enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Day today = Wednesday; // 'Wednesday' is an enum constant
By default, SUNDAY = 0, MONDAY = 1, and so on.
enum Day { Sunday = 1, Monday, Tuesday = 10 };
Symbolic Constants:
Symbolic constants are values assigned a name using #define or the const keyword. Values defined using this cannot
be changed.
Example: #define PI 3.14159
Escape Sequence
\b (Backspace) - Moves the cursor one place backward.
\t (Horizontal tab) - Inserts some whitespace to the left of the cursor.
\n (New line) - Moves the cursor to the start of the next line.
\v (Vertical tab) - Inserts vertical space, moves the cursor downwards (if supported by the system).
\a (Alert/Bell) - Produces a beep sound (if supported by the system).
\f (Form Feed) - Moves to the next page (if supported by the system).
\r (Carriage Return) - Moves the cursor to the start of the line (overwrites existing text) (if supported by the system).
\0 (Null Character) - represents the end of a string in C-style strings.
Variables and Declaration
A variable is used to store values. And before using a variable, you must declare it by specifying its datatype.
Example: int age = 25; // Declares a variable 'age' type integer and assigns the value 25 to 'age'
Reference Variables
A reference variable is like an alternative name for an existing variable. It doesn't create a new variable but gives
another name to an existing one.
Unary Operators
Unary operators are operators that work on a single operand
int a = 10;
int b = -a; // Unary minus applied, now b is -10
int a = -10;
int b = -a; // Unary minus applied, now b is 10
Increment (++)
Adds 1 to a variable.
++x (Pre-increment) → First increase, then use the value.
x++ (Post-increment) → First use the value, then increase.
Decrement (--)
Subtracts 1 from a variable.
--x (Pre-decrement) → First decrease, then use the value.
x-- (Post-decrement) → First use the value, then decrease.
!true → false
!false → true
sizeof() Operator
This operator tells you the size (in bytes) of a variable or data type.
sizeof(int);
Relational Operators: Relational operators compare two values and return a Boolean result (true or false).
They help in decision-making. These operators return true (1) or false (0).
Less Than (<) Checks if the left value is smaller than the right value.
Less Than or Equal To (<=) Checks if the left value is smaller than OR equal to the right value.
Greater Than (>) Checks if the left value is greater than the right value.
Greater Than or Equal To (>=) Checks if the left value is greater than OR equal to the right value.
Equality Operators: These operators are used to compare values and return true or false.
Example:
int min = (x < y)? x : y; // If x < y, return x, else return y
Assignment Operators
Operator Meaning Example
= Assigns a value A = 5;
+= Adds and assigns a += 2; (same as a = a + 2)
-= Subracts and assigns a -= 2; (same as a = a - 2)
*= Multiplies and assigns a *= 2; (same as a = a * 2)
/= Divides and assigns a /= 2; (same as a = a / 2)
%= Modulus and assigns a %= 2; (same as a = a % 2)
Scope Resolution Operator (::) Used to access global variables or class members when they are hidden by
local variables.
Example:
int* ptr = new int; // Allocates memory for an integer
int* arr = new int[10]; // Allocate memory for an array of 10 integers
delete ptr; // Frees the allocated memory
delete[] arr; // Deallocate memory for the array of integers
Using cin and cout with Insertion (<<) and Extraction (>>)
cout (Output) Uses << (Insertion Operator)
cout is used to display output on the screen. The insertion operator (<<) sends data to cout.
Example:
cout << "Hello, World!"; // Output: Hello, World!
Example:
Int age
cout << "Enter your age: ";
cin >> age; // Takes user input and stores it in 'age'
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b; // Takes two inputs
Manipulators: Manipulators help format output by adjusting spaces, decimal precision, alignment, etc.
What is <iomanip>?
<iomanip> (I/O Manipulators Header) allows us to control output formatting like width, precision, and alignment in
cout output.
Example: cout << setw(10) << "Hello" << setw(10) << "World";
2. endl – New Line (Moves the output to a new line (same as \n)). Also flushes the output buffer.
Output: Hello
World
Output: 3.14
4. setfill(c) – Fills empty spaces with a specified character. Works with setw().
Output: ********Hi
Output: Hi
Output: Hi
Output: 1.234568e+04
Output: 3.14
ios::showpos – Show Positive Sign (+), Forces cout to show + before positive numbers.
Output: +10
ios::showpoint – Show Decimal Point, Ensures decimal points are always shown. Even if no decimal part exists.
Example: cout << showpoint << fixed << setprecision(0) << 10.0;
ios::unitbuf – Auto Flush Output Buffer. Automatically flushes cout after every output operation.
Use of an Editor
An editor is a tool which is used to write and edit your C++ code.
Popular C++ Editors: Code::Blocks, Turbo C++ ,Notepad++, Dev-C++, Visual Studio Code (VS Code)
Execution Process
./program # Linux/Mac
program.exe # Windows
Debugging: Debugging means finding and fixing errors (bugs) in the code.
Types of Errors:
Syntax Errors → Mistakes in code structure (e.g., missing ;)
Runtime Errors → Errors that happen while running the program (e.g., division by zero).
Logical Errors → Wrong output due to incorrect logic.
Control Statements
If-Else Statement: The if-else statement is used to execute code only if a condition is true.
if (condition) {
// Code executes if the condition is true
} else {
// Code executes if the condition is false
}
if (condition) {
// Code executes if the condition is true
} elseif (condition) {
// Code executes if the condition is true
}else {
// Code executes if the conditions are false
}
While Loop: The while loop repeats a block of code as long as the condition is true.
while (condition) {
// Code runs repeatedly until the condition becomes false
}
Do-While Loop: The do-while loop executes the block at least once, even if the condition is false.
do {
// Code executes at least once
} while (condition);
For Loop: The for loop is used when we know how many times we want to execute a loop.
Break Statement: The break statement stops a loop or switch statement immediately.
Continue Statement: The continue statement skips the rest of the loop body and moves to the next iteration.
Switch Statement: The switch statement checks multiple conditions using a case.
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Comma Operator (,): The comma , operator executes multiple expressions in a single statement.
Example:
#include <iostream>
using namespace std;
int main() {
for (int i = 0, j = 5; i < 5; i++, j--) {
cout << "i: " << i << ", j: " << j << endl;
}
return 0;
}
Functions in Programming
Definition: A function is a self-contained block of code that performs a specific task. It helps in code reusability,
modularity, and readability.
Concept of Functions: Functions break a large program into smaller, manageable parts. They take input
(parameters), process it, and return output. Functions can be user-defined or built-in.
Syntax:
return_type function_name(parameters) {
// function body
return value; // (if applicable)
}
Example:
int add(int a, int b) {
return a + b;
}
Function Declaration (Prototype): The function declaration, also known as the function prototype, informs the
compiler about the function's name, return type, and parameters, without providing the actual body of the function.
It usually appears before the main() function.
Syntax:
return_type function_name(parameter_list);
Example:
int add(int, int); // Function prototype
Function Definition: The function definition provides the actual body of the function, specifying the code that
will run when the function is called.
Global Variables: Declared outside all functions. Accessible to all functions in the program.Retains its value
throughout the program's execution.
Function Call: A function call is when you use a function's name and pass any required arguments to execute the
function's code.
In C++, when calling a function, arguments can be passed in three ways, each method determines whether changes
inside the function affect the original variable.:
Example:
#include <iostream>
using namespace std;
void modify(int x) {
x = x + 10; // Only the local copy of x changes
cout << "Inside function: x = " << x << endl;
}
int main() {
int a = 5;
modify(a); // Passing a COPY of a
cout << "Outside function: a = " << a << endl; // Original 'a' remains unchanged
return 0;
}
Output:
Inside function: x = 15
Outside function: a = 5
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5;
modify(&a); // Passing the ADDRESS of 'a' using '&'
cout << "Outside function: a = " << a << endl; // 'a' gets modified
return 0;
}
Output:
Inside function: x = 15
Outside function: a = 15
int main() {
int a = 5;
modify(a); // Passing variable as a reference
cout << "Outside function: a = " << a << endl; // 'a' gets modified
return 0;
}
Example:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
Return by Reference: Instead of returning a copy, a function can return a reference to a variable.
This allows modifications to affect the original variable.
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
getMax(a, b) = 50; // Modifies the larger value
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Output: a = 10, b = 50
Inline Functions: The compiler replaces the function call with the function's body during compilation. Useful for
small functions and this makes execution faster..
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Sum: " << add(5, 3) << endl;
cout << "Sum: " << add(10, 7) << endl;
return 0;
}
Output: Sum: 8
Sum: 17
Functions with Default Parameters: We can set default values for parameters. If a function call does not
provide values, the default values are used.
Example:
#include <iostream>
using namespace std;
int main() {
greet(); // Uses default value "Guest"
greet("Alice"); // Uses provided value "Alice"
return 0;
}
Output:
Hello, Guest!
Hello, Alice!
Function Overloading: Function overloading allows multiple functions with the same name but different
parameters. The compiler decides which function to call based on the arguments.
Example:
#include <iostream>
using namespace std;
void print(int x) {
cout << "Integer: " << x << endl;
}
void print(double x) {
cout << "Double: " << x << endl;
}
void print(string x) {
cout << "String: " << x << endl;
}
return 0;
}
Output:
Integer: 10 Double: 5.5 String: Hello X: 5 Z: 5.5
Built-in Functions:
String functions like strlen(), strcpy(), strcmp(), and strcat() are functions from the <string.h>/< cstring > library
strlen() — Find the Length of a String The strlen() function is used to find the length of a string.
strcpy() — Copy a String The strcpy() function copies one string into another.
strcmp() — Compare Two Strings The strcmp() function compares two strings.
strcat() — Concatenate Two Strings The strcat() function concatenates (appends) one string to the end of another.
Example:
#include <iostream>
#include <cstring> // For string functions
using namespace std;
int main() {
char str1[20] = "Hello"; char str2[20] = "World";
cout << "Length of str1: " << strlen(str1) << endl; // strlen()
cout << "Comparing 'New' and 'World': " << strcmp(str1, str2) << endl; // strcmp()
return 0;
}
Output:
Length of str1: 5
Concatenated string: HelloWorld
After strcpy: New
Comparing 'New' and 'World': -1 (or other number negative number)
Mathematical functions like log(), log10(), pow(), sqrt(), sin(), cos(), and abs() are part of the <math.h> library.
log(x) - Returns the natural logarithm of x (base e)
log10(x) - Returns logarithm of x (base 10)
pow(x, y) - Returns x raised to the power y
sqrt(x)- Returns the square root of x
sin(x) - Returns the sine of x (radians)
cos(x) - Returns the cosine of x (radians)
abs(x) - Returns the absolute value of x
Example:
#include <iostream>
#include <math.h> // For math functions
using namespace std;
int main() {
cout << "log(10): " << log(10) <<”, log10(100): " << log10(100) <<”, pow(2, 3): " << pow(2, 3) <<”,” ;
cout << "sqrt(16): " << sqrt(16) <<”, sin(90 degrees): " << sin(90 * 3.14159 / 180) <<”,” ;
cout << "cos(0 degrees): " << cos(0) <<”,” ;
cout << "abs(-5): " << abs(-5) ;
return 0;
}
Output:
log(10): 2.30258, log10(100): 2, pow(2, 3): 8, sqrt(16): 4, sin(90 degrees): 1, cos(0 degrees): 1, abs(-5): 5
Character functions like isalnum(), isdigit(), islower(), isupper(), isalpha(), toupper(), and tolower() are part of the
<ctype.h> / <cctype> library.
Input/Output Functions fgets(), puts(), getchar(), putchar() are part of the <cstdio>/ <stdio.h> library.
Example:
#include <iostream>
#include <cstdio> // For gets(), puts(), getchar(), putchar()
using namespace std;
int main() {
char str[50]; char ch;
return 0;
}
These functions clrscr(), getch() are part of the <conio.h> library.
In modern C++, use system("CLS") instead of clrscr(), and cin.get() instead of getch().
Benefits of OOP:
Modular Code – Code is divided into classes and objects.
Reusability – Code can be reused using inheritance.
Data Security – Data is hidden using encapsulation.
Easier Maintenance – Code is structured, making it easy to manage.
Objects and Classes:
Class: A blueprint for creating objects (e.g., a "Car" class).
Object: A specific instance of a class (e.g., "Toyota" is an object of "Car" class).
// Defining a class
class Car {
public:
string brand; // Attribute
int speed; // Attribute
int main() {
Car myCar; // Creating an object
myCar.brand = "Toyota";
myCar.speed = 120;
return 0;
}
Output:
Car brand: Toyota, Speed: 120 km/h
Data Abstraction: Abstraction means hiding unnecessary details and showing only the essential features.
Example: A car has a steering wheel, but we don't need to know how the engine works to drive it.
Example:
#include <iostream>
using namespace std;
class ATM {
private:
int pin; // Hidden data (cannot be accessed directly)
public:
void setPin(int p) { pin = p; } // Only way to set pin
void showMessage() { cout << "Welcome to ATM!" << endl; }
};
int main() {
ATM myATM;
myATM.setPin(1234); // User sets pin
myATM.showMessage(); // Only the essential feature is shown
return 0;
}
Example:
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // Private data (cannot be accessed directly)
public:
void deposit(double amount) { balance += amount; }
void showBalance() { cout << "Balance: $" << balance << endl; }
};
int main() {
BankAccount myAccount;
myAccount.deposit(500); // Data modified through method
myAccount.showBalance(); // Display balance
return 0;
}
Output:
Balance: $500
Inheritance: Inheritance allows a class to reuse properties of another class. The child class (derived class) inherits
from the parent class (base class).
Example:
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void eat() { cout << "I can eat!" << endl; }
};
// Derived class
class Dog : public Animal {
public:
void bark() { cout << "I can bark!" << endl; }
};
int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog class
return 0;
}
Output:
I can eat!
I can bark!
Polymorphism: Polymorphism means "many forms." A function or method behaves differently based on the object
calling it. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one
form.
Types of Polymorphism
Function Overloading: When there are multiple functions with the same name but different parameters.
Operator Overloading: C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition operator (+) for string class
to concatenate two strings.
Example:
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
virtual void makeSound() { cout << "Animal makes a sound!" << endl; }
};
// Derived class
class Dog : public Animal {
public:
void makeSound() override { cout << "Dog barks!" << endl; }
};
int main() {
Animal* myAnimal;
Dog myDog;
myAnimal = &myDog;
myAnimal->makeSound(); // Calls overridden method in Dog class
return 0;
}
Output:
Dog barks!
Object: An object is an instance of a class. It is created using the class definition and can access the data members
and member functions.
Example:
class Car {
public:
string brand;
int year;
};
Defining Member Functions Inside the Class:
class Car {
public:
string brand; int year;
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
Outside the Class: Functions can also be defined outside the class using the scope resolution operator (::).
class Car {
public:
string brand;
int year;
Creating Objects
Example:
int main() {
Car myCar; // Creating an object
myCar.brand = "Toyota";
myCar.year = 2022;
Array of Objects
Example:
class Car {
public:
string brand;
int year;
};
int main() {
Car cars[2]; // Array of objects
cars[0].brand = "Honda";
cars[0].year = 2018;
cars[1].brand = "Ford";
cars[1].year = 2020;
cout << "Car 1: " << cars[0].brand << ", " << cars[0].year << endl;
cout << "Car 2: " << cars[1].brand << ", " << cars[1].year << endl;
return 0;
}
Objects as Function Arguments
Example:
class Car {
public:
string brand;
int year;
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car myCar;
myCar.brand = "Tesla";
myCar.year = 2023;
Example:
class Car {
public:
string brand; int year;
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car myCar = createCar(); // Storing returned object
myCar.display(); // Calling function
return 0;
}
Characteristics of a Constructor: Same name as the class, No return type (not even void), Automatically
invoked when an object is created, Can be overloaded (multiple constructors with different parameters), Can have
default arguments
Default Constructor: A default constructor is a constructor that takes no parameters. It initializes object data
with default values.
Example:
#include <iostream>
using namespace std;
class Car {
public:
string brand; int year;
// Default Constructor
Car() {
brand = "Unknown";
year = 0;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car myCar; // Default constructor is called
myCar.display();
return 0;
}
Output:
Brand: Unknown, Year: 0
Constructor with Default Arguments: A constructor can have default arguments, allowing us to pass fewer
arguments when creating an object.
Example:
#include <iostream>
using namespace std;
class Car {
public:
string brand; int year;
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1; // Uses default values
Car car2("Honda"); // Uses default year
Car car3("Ford", 2022);
car1.display();
car2.display();
car3.display();
return 0;
}
Output:
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2020
Brand: Ford, Year: 2022
Parameterized Constructor: A parameterized constructor takes arguments to initialize an object with specific values.
class Car {
public:
string brand; int year;
// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1("Tesla", 2023); // Implicit call
Car car2 = Car("BMW", 2021); // Explicit call
car1.display();
car2.display();
return 0;
}
Constructor Overloading: We can define multiple constructors with different parameters (overloading).
EXAMPLE:
#include <iostream>
using namespace std;
class Car {
public:
string brand; int year;
// Default Constructor
Car() {
brand = "Unknown";
year = 0;
}
// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1; // Calls default constructor
Car car2("Audi", 2022); // Calls parameterized constructor
car1.display();
car2.display();
return 0;
}
Copy Constructor: A copy constructor creates a new object by copying an existing object.
EXAMPLE:
#include <iostream>
using namespace std;
class Car {
public:
string brand; int year;
// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}
// Copy Constructor
Car(const Car &c) {
brand = c.brand;
year = c.year;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1("Mercedes", 2023);
Car car2 = car1; // Copy constructor is called
car1.display();
car2.display();
return 0;
}
EXAMPLE:
#include <iostream>
using namespace std;
class Car {
public:
string *brand;
// Constructor
Car(string b) {
brand = new string(b); // Dynamic memory allocation
}
void display() {
cout << "Brand: " << *brand << endl;
}
int main() {
Car car1("Lamborghini");
car1.display();
return 0;
}
Dynamic Initialization of Objects: Objects can be dynamically initialized at runtime using a constructor.
EXAMPLE:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
string b; int y;
Destructor: A destructor is a special member function that is automatically called when an object is destroyed. It
cleans up resources allocated by an object.
Characteristics of Destructor: Same name as the class, but preceded by ~ (tilde), No return type and no parameters,
automatically invoked when an object goes out of scope, Only one destructor per class (cannot be overloaded)
Example:
#include <iostream>
using namespace std;
class Car {
public:
Car() {
cout << "Car created!" << endl;
}
~Car() {
cout << "Car destroyed!" << endl;
}
};
int main() {
Car myCar; // Constructor is called
return 0; // Destructor is called automatically
}
Inheritance:
Inheritance is a fundamental concept that enables a new class to inherit properties (attributes and methods) from
an existing class. This relationship allows for the reuse and extension of code, creating a hierarchy of classes that can
share and build upon each other’s functionality.
Key Concepts of Inheritance
• Base (or Parent) Class: The base class (also known as the parent or superclass) is the class whose properties
and methods are inherited by other classes. It contains common functionality that can be shared across
multiple derived classes.
• Derived (or Child) Class: The derived class (also known as the child or subclass) is a class that inherits
properties and methods from the base class. It can use the features of the base class and can also extend or
modify the inherited properties and behaviors to suit its specific needs.
Basic Syntax of Inheritance: In C++, inheritance is specified using a colon (:) followed by the access specifier (such as
public) and the name of the base class:
class BaseClass {
// Properties and methods of the base class
};
Example:
#include <iostream>
#include <string>
// Base class
class Animal {
public:
void eat() {
std::cout << "This animal is eating." << std::endl;
}
};
// Derived class
class Dog : public Animal {
public:
void bark() {
std::cout << "The dog is barking." << std::endl;
}
};
int main() {
Dog myDog;
return 0;
}
Abstract Classes:
An abstract class is a class that is designed to be inherited by other classes but is not meant to be instantiated
directly. It usually includes pure virtual functions, which are declared by assigning 0 to a virtual function. These pure
virtual functions force derived classes to implement their own versions, making the abstract class serve as a
blueprint for the derived classes.
Example:
#include <iostream>
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
int main() {
Circle circle;
circle.draw(); // Calls the derived class implementation
return 0;
}
In this example: Circle inherits from Shape and provides an implementation for the draw() function, Shape serves as
an abstract base class that defines a common interface for all shapes.
Types of Inheritance:
Single Inheritance: A derived class inherits from only one base class.
class A { /* Base class */ };
class B : public A { /* Derived class */ };
Multiple Inheritance: A derived class inherits from more than one base class.
class A { /* Base class */ };
class B { /* Another base class */ };
class C : public A, public B { /* Derived class */ };
Multilevel Inheritance: A class is derived from a class that is also derived from another class.
class A { /* Base class */ };
class B : public A { /* Intermediate derived class */ };
class C : public B { /* Final derived class */ };
Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
class A { /* Base class */ };
class B : public A { /* Derived class */ };
class C : public A { /* Another derived class */ };
Hybrid Inheritance: A combination of multiple and multilevel inheritance. It is a complex inheritance structure
that can lead to a diamond problem (resolved in C++ by virtual inheritance).
class Vehicle { // Base class };
class Engine : public Vehicle { // Derived from Vehicle };
class Wheels : public Vehicle { // Derived from Vehicle };
class Car : public Engine, public Wheels { // Derived from both Engine and Wheels, creating a hybrid structure };
Access Specifiers in Inheritance
The access specifier (public, protected, private) used in inheritance determines how the members of the base class
are inherited:
• Public Inheritance: Public members of the base class remain public in the derived class, and
protected members remain protected.
• Protected Inheritance: Public and protected members of the base class become protected in the
derived class.
• Private Inheritance: Public and protected members of the base class become private in the derived
class.
Benefits of Inheritance
• Code Reusability: Inheritance allows classes to reuse code from other classes, reducing duplication
and making code maintenance easier.
• Extensibility: New features can be added to derived classes without modifying the base class.
Derived classes
Derived classes allow new classes to inherit properties and behaviors from existing classes, forming relationships
that enable code reuse and extensibility. Derived classes are defined using inheritance with visibility modes and can
use constructors to initialize inherited properties.
Visibility Modes- visibility mode (or access specifier) determines how the members of the base class are accessed in
the derived class. In C++, the three visibility modes are:
1. Public: Members of the base class retain their original access levels in the derived class.
2. Protected: Public and protected members of the base class become protected in the derived class.
3. Private: All inherited members of the base class become private in the derived class.
Types of Derivation
1. Public Derivation
• The public members of the base class remain public in the derived class.
• The protected members of the base class remain protected in the derived class.
• The private members of the base class are inaccessible in the derived class.
Example:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
2. Private Derivation
• Both public and protected members of the base class become private in the derived class.
• The private members of the base class remain inaccessible in the derived class.
Example:
class Derived : private Base {
// publicMember becomes private in Derived
// protectedMember becomes private in Derived
// privateMember is inaccessible in Derived
};
3. Protected Derivation
• Both public and protected members of the base class become protected in the derived class.
• The private members of the base class remain inaccessible in the derived class.
Example:
class Derived : protected Base {
// publicMember becomes protected in Derived
// protectedMember remains protected in Derived
// privateMember is inaccessible in Derived
};
Constructors in Derived Classes: Constructors of the base class are not inherited by the derived class. when a
derived class is instantiated, the base class constructor is called first, followed by the derived class constructor. This
ensures that the base part of the derived object is properly initialized before any additional initialization in the
derived class.
Program of Calling the Base Class Constructor:
Example:
#include <iostream>
class Base {
public:
Base(int x) {
std::cout << "Base constructor called with x = " << x << std::endl;
}
};
int main() {
Derived obj(10, 20);
return 0;
}
Containership: (also known as composition) is a form of association where one class contains objects of another
class as its members, rather than inheriting from it. This is often used to represent a “has-a” relationship.
Composition is used when you want to use the functionality of other classes within a class but don't require an
inheritance relationship.
Program of Containership:
Example:
#include <iostream>
class Engine {
public:
Engine() { std::cout << "Engine created\n"; }
void start() { std::cout << "Engine started\n"; }
};
class Car {
private:
Engine engine; // Car "has-an" Engine
public:
Car() { std::cout << "Car created\n"; }
void start() {
engine.start(); // Using Engine’s functionality within Car
std::cout << "Car started\n";
}
};
int main() {
Car myCar;
myCar.start();
return 0;
}
Example:
#include <iostream>
class Person {
public:
Person() {
std::cout << "Person Constructor" << std::endl;
}
};
int main() {
TeachingAssistant ta;
return 0;
}