0% found this document useful (0 votes)
3 views36 pages

OOPs C++

The lesson plan covers Object-Oriented Programming (OOP) concepts in C++, including classes, objects, inheritance, polymorphism, and encapsulation. It contrasts the array approach with the class approach, emphasizing the benefits of OOP for managing complex programs. Additionally, it includes practical examples, access specifiers, and methods for initializing and accessing class variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

OOPs C++

The lesson plan covers Object-Oriented Programming (OOP) concepts in C++, including classes, objects, inheritance, polymorphism, and encapsulation. It contrasts the array approach with the class approach, emphasizing the benefits of OOP for managing complex programs. Additionally, it includes practical examples, access specifiers, and methods for initializing and accessing class variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Lesson Plan

OOPs C++
Today’s checklist:

OOP concept

Array Vs Structur

Classe

Constructor

Inheritanc

Function overloadin

Function overridin

MCQs & predict the output questions

Object-Oriented Programming (OOP) is like organizing a toolbox. Imagine you have different tools (like a
hammer, screwdriver, and wrench) in a toolbox. Each tool has its own unique purpose and characteristics,
right? That's similar to how OOP works.

Class: Think of a class as a blueprint or a template. It defines the properties (attributes) and behaviors (actions
or methods) that objects made from it will have. For instance, if "Car" is a class, it defines what a car is made of
(like wheels, color, model) and what it can do (drive, honk).

Object: Now, when you use that blueprint to create an actual object, it's like making a real car from the "Car"
blueprint. This object will have specific values for its properties defined in the class. So, you might have a
specific car object named "MyCar" that has four wheels, is red, and is a specific model.

OOP helps in managing big programs by breaking them into smaller, manageable parts (classes). It makes it
easier to reuse code, change things without affecting the whole program, and organize everything neatly.

Java
C++ &+ DSA
DSA
Data Abstraction: OOP allows the creation of complex data types where the implementation details are hidden,
offering only essential information and functionalities. Users interact with objects through interfaces, ignoring
underlying complexities.

Data Encapsulation: This is about bundling data (attributes or properties) and the methods that operate on the
data within a single unit, i.e., an object. Encapsulation provides data protection and control by restricting access
to certain parts of the object.

Inheritance: Inheritance allows a class to inherit properties and behavior from another class. It promotes code
reuse and establishes a hierarchical relationship between classes, enabling new classes to take on
characteristics of existing classes.

Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common


superclass. It enables methods to be invoked on objects without needing to know the specific class. This helps
in writing more flexible and reusable code.

Java
C++ &+ DSA
DSA
Polymorphism

Compile time
Run time

Polymorphism Polymorphism

Function
Operator
Virtual

Overloading Overloading Function

What are classes?


Class is a user-defined datatype.

class Player {

int health;

int score;

String name;

What are Objects?

Object is an instance of the class.


class Player {

int health;

int score;

String name;

Player harsh;

Here harsh is an object of class Player

Why Classes?
Classes enable us to apply OOP concepts like

Data Abstractio
Data Encapsulatio
Inheritanc
Polymorphis
Modularity and Reusability: Once a class is defined, it can be used to create multiple objects across the
program.

Java
C++ &+ DSA
DSA
Array approach Vs Class

Array Approach:

Structure: Stores elements of the same type in contiguous memory.

Fixed Size: Size is fixed and declared at compile-time.

Direct Access: Accessed by indices, providing fast access.

Homogeneous: Suitable for storing the same type of data.

Limited Functionality: Lacks built-in features like methods and dynamic resizing.

Class Approach:

Structure: Blueprint for creating objects with data and methods.

Encapsulation: Encapsulates data and methods, offering better control and abstraction.

Dynamic Memory: Supports dynamic memory allocation, enabling resizing.

Flexibility: Allows for heterogeneous data and complex functionalities.

Polymorphism & Inheritance: Supports these concepts for code reuse and relationships between objects.

In essence, arrays are simple, fixed-size collections ideal for homogeneous data, offering uick access. Classes
q

provide flexibility, encapsulation, and dynamic memory, suitable for complex structures with diverse data and

functionalities. The choice depends on the program's complexity and requirements.

Class Variables: In C++, class variables, also known as member variables or attributes, are declared within the

class definition. They can be initialized in various ways and accessed using object instances or within member

functions of the class.

Declaration:

Here's how you declare class variables within a class definition:

class MyClass {

public:

int myInt; // Example integer variable

double myDouble; // Example double variable

// Other member functions or variables can be declared here

};

Java
C++ &+ DSA
DSA
Initialization:

There are several ways to initialize class variables:

Default Initialization:

MyClass obj;

obj.myInt = 10; // Assigning a value to myInt after object creation

obj.myDouble = 5.5; // Assigning a value to myDouble after object creation

Constructor Initialization:

class MyClass {

public:

int myInt;

double myDouble;

// Constructor to initialize variables during object creation

MyClass(int i, double d) : myInt(i), myDouble(d) {}

};

// Creating an object and initializing variables using the

constructor

MyClass obj(10, 5.5);

Accessing Class Variables:

You can access class variables using object instances:

MyClass obj;

obj.myInt = 20; // Assigning a value to myInt

double val = obj.myDouble; // Accessing myDouble and storing its value

Accessing Variables within Member Functions:

Within member functions of the class, you can directly access class variables:

class MyClass {

public:

int myInt;

double myDouble;

void display Values() {

cout << "MyInt: " << myInt << endl; // Accessing myInt

cout << "MyDouble: " << myDouble << endl ; // Accessing


myDoubl e

};

Java
C++ &+ DSA
DSA
// Using the member function to display values

MyClass obj;

obj.myInt = 30;

obj.myDouble = 7.7;

obj.displayValues(); // Outputting the values using the member function

These approaches demonstrate how to declare, initialize, and access class variables in C++. The choice of
initialization method depends on the context and requirements of your program.

Access specifiers:

Access Specifiers in C++ Classes:

1. Public:

Accessible from anywhere


Can be accessed by objects of the class and from outside the class.

2. Private:

Accessible only within the class itself


Not accessible or modifiable directly from outside the class.

3. Protected:

Similar to private but accessible in derived classes


Not accessible from outside the class, but available to derived classes.

### Usage:

Public members are accessible directly from objects


Private members cannot be accessed directly; often accessed/modified using public member functions
Protected members are accessible within derived classes but not directly from outside.

class MyClass {

public:

int publicVar; // Public variable

// ...

private:

int privateVar; // Private variable

// ...

protected:

int protectedVar; // Protected variable

// ...

};

Understanding these specifiers helps control access to class members, ensuring proper encapsulation and
abstraction in C++ programs.

Java
C++ &+ DSA
DSA
Getters and Setters:
Getters: Functions used to access or retrieve the value of a private member variable.
Example:

class MyClass {

private:

int myVar;

public:

int getMyVar() {

return myVar;

};

Setters: Functions used to modify or set the value of a private member variable.
Example:

class MyClass {

private:

int myVar;

public:

void setMyVar(int value) {

myVar = value;

};

Usage:
Getters allow accessing private variables from outside the class
Setters enable modifying private variables in a controlled manner.
//Code:
MyClass obj;

int value = obj.getMyVar(); // Using getter to access myVar

obj.setMyVar(10); // Using setter to modify myVar


Getters and setters facilitate controlled access and modification of private member variables, maintaining
encapsulation in C++ classes.

Q. Create a class ‘book’ with name, price, and number of pages as its attributes. The class should contain the
following member functions :

countBooks(int price): This function will return count of all the books that have a price less than the given
price.

isBookPresent(string title) : This will return a boolean value indicating whether any book with the given title
exists or not.

Java
C++ &+ DSA
DSA
Class: Book
#### Attributes:

Name: Title of the boo


Price: Cost of the boo
Number of Pages: Total pages in the book

#### Member Functions:

1. countBooks(int price):
Return Type: Intege
Description: Counts books with prices less than the given value.

2. isBookPresent(string title):
Return Type: Boolea
Description: Checks if a book with the specified title exists.

Implementation Overview:
The `Book` class encapsulates book attributes: name, price, and number of pages
`countBooks(int price)` returns the count of books with prices lower than the given value
`isBookPresent(string title)` checks for the existence of a book by title, returning a boolean value.

Example Usage:

Code:

class Book {

private:

string name;

int price;

int pages;

public:

// Constructor, other member functions

int countBooks(int price) {

// Implementation to count books with price less than


given value

bool isBookPresent(string title) {

// Implementation to check if a book with given title


exists

};

Java
C++ &+ DSA
DSA
// Usage example

Book book1; // Create a book object

int count = book1.countBooks(50); // Get count of books cheaper than $50

bool exists = book1.isBookPresent("Title"); // Check if a book with title "Title" exists

Functionality:
countBooks(int price): Helps in finding the count of books priced below a specified value
isBookPresent(string title): Determines whether a book with a specific title exists or not.

These functions enable users to efficiently manage and query book information based on price and title,
respectively, promoting ease of book inventory management.

Passing class objects to functions


Passing class objects to functions in C++ involves either passing by value or passing by reference:

### Passing by Value:


Function receives a copy of the object
Changes made to the object within the function don't affect the original.
Example:

class MyClass {

// Class definition

};

void funcByValue(MyClass obj) {

// Code manipulating the copy of obj

int main() {

MyClass obj;

funcByValue(obj); // Passing object by value

// Changes to obj in funcByValue won't affect the original


obj

return 0;

### Passing by Reference:


Function works directly with the original object
Changes made within the function affect the original object.

Example:

class MyClass {

// Class definition

};

C++ &+ DSA


Java DSA
void funcByReference(MyClass &obj) {

// Code manipulating the original obj

int main() {

MyClass obj;

funcByReference(obj); // Passing object by reference

// Changes to obj in funcByReference affect the original obj

return 0;

Choose between passing by value or reference based on whether modifications to the original object within the
function are necessary or not. Passing by reference is more efficient for large objects and when changes to the
original object are needed within the function.

Static Allocation vs Dynamic Allocation


Static Allocation in OOP (C++):

Code:

class StaticObject {

// Class definition

};

int main() {

StaticObject obj1; // Object created at compile time

// Memory allocated on the stack

// Size determined at compile time

// Use obj1...

return 0;

Explanation:

Static Allocation
`StaticObject` is created at compile time
Memory is allocated on the stack
The size of `obj1` is determined at compile time
Automatic memory management within the scope of `main`.

Java
C++ &+ DSA
DSA
Dynamic Allocation in OOP (C++):

Code:

class DynamicObject {

// Class definition

};

int main() {

DynamicObject *obj2 = new DynamicObject(); // Object created


at runtime

// Memory allocated on the heap

// Size and memory allocation happen during runtime

// Use obj2...

delete obj2; // Manual deallocation to prevent memory leaks

return 0;

Explanation:
Dynamic Allocation
`DynamicObject` is created at runtime using `new`
Memory is allocated on the heap
Size and memory allocation occur during runtime
Manual deallocation (`delete obj2`) is required to release memory and avoid memory leaks.

Class in Class - Nested Class


Nested Class in C++:
Definition:
Nested Class: A class defined within another class.
Syntax:

class OuterClass {

// Outer class definition

class NestedClass {

// Nested class definition

};

};

Characteristics:
Access: Nested class has access to private members of the outer class
Scope: Outer class name must be used to access the nested class from outside the outer class
Encapsulation: Provides a way to encapsulate related classes.

Java
C++ &+ DSA
DSA
Example:

class OuterClass {

private:

int outerVar;

public:

class NestedClass {

public:

void display(OuterClass obj) {

cout << "Outer variable value: " << obj.outerVar <<

endl;

};

};

int main() {

OuterClass outerObj;

OuterClass::NestedClass nestedObj;

nestedObj.display(outerObj); // Accessing nested class method

using outer class object

return 0;

Usage:

Organization: Group related classes together

Access Control: Nested class can access private members of the outer class

Scoping: Use the `OuterClass::NestedClass` syntax to access the nested class outside the outer class.

Array of Classes in C++:

Declaration:

Use the class name followed by square brackets and the array size to create an array of objects of that

class.

Example:

class MyClass {

// Class definition

};

int main() {

const int arraySize = 5;

MyClass myArray[arraySize]; // Array of MyClass objects

Java
C++ &+ DSA
DSA
// Access and use array elements as needed

myArray[0].someFunction(); // Accessing methods or attributes


of an object in the array

return 0;

Array of classes allows creating multiple objects of the same class in a contiguous block of memory, accessed
via array indexing.

Q. Create a class “cricketer” that contains name of cricketer, his age, number of test matches that he has
played and the average runs that he has scored in each test match. Create an array of data type “cricketer”
to hold records of 20 such cricketers and then write a program to read these records.

#include <iostream>

#include <string>

using namespace std;

class Cricketer {

public:

string name;

int age;

int numTests;

double avgRuns;

// Method to input cricketer details

void inputCricketer() {

cout << "Enter Cricketer's Name: ";

cin >> name;

cout << "Enter Age: ";

cin >> age;

cout << "Enter Number of Test Matches Played: ";

cin >> numTests;

cout << "Enter Average Runs Scored per Test: ";

cin >> avgRuns;

// Method to display cricketer details

void displayCricketer() {

cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

cout << "Test Matches Played: " << numTests << endl;

cout << "Average Runs per Test: " << avgRuns << endl;

};

int main() {

const int numCricketers = 20;

Cricketer cricketers[numCricketers]; // Array to hold


cricketer records

Java
C++ &+ DSA
DSA
// Input cricketer records

for (int i = 0; i < numCricketers; ++i) {

cout << "Enter details for Cricketer " << i + 1 << ":" <<
endl;

cricketers[i].inputCricketer();

// Display cricketer records

for (int i = 0; i < numCricketers; ++i) {

cout << "Cricketer " << i + 1 << " Details:" << endl;

cricketers[i].displayCricketer();

cout << endl;

return 0;

This code defines a `Cricketer` class with attributes for name, age, number of tests played, and average runs
per test. It then creates an array of `Cricketer` objects to store details for 20 cricketers, allowing the user to input
and display those records.

Constructors: Constructors are special member functions in classes that are automatically called when an
object of that class is created. They initialize the object's attributes, allocate resources if necessary, and set up
the object to be used.

Types of Constructors:
Default Constructor:
No parameters
Automatically called when an object is created without arguments
Initializes member variables to default values.
Parameterized Constructor:
Accepts parameters to initialize object attributes
Allows custom initialization of object attributes during object creation.
Copy Constructor:
Creates a new object as a copy of an existing object
Copies the values of attributes from one object to another.
Example:

class Car {

public:

string make;

string model;

int year;

Java
C++ &+ DSA
DSA
// Default Constructor

Car() {

make = "DefaultMake";

model = "DefaultModel";

year = 2020;

// Parameterized Constructor

Car(string mk, string md, int yr) {

make = mk;

model = md;

year = yr;

// Copy Constructor

Car(const Car &car) {

make = car.make;

model = car.model;

year = car.year;

};

int main() {

// Using constructors to create objects

Car defaultCar; // Default Constructor called

Car customCar("Toyota", "Corolla", 2015); // Parameterized


Constructor called

Car copiedCar = customCar; // Copy Constructor called

return 0;

Constructors allow initialization of object attributes when creating objects, enabling custom setups based on
specific requirements.
Destructor:
Definition: Special member function with the same name as the class, preceded by a tilde (`~`)
Purpose: Performs cleanup tasks when the object goes out of scope or is explicitly deleted
Automatic Invocation: Called automatically when the object is destroyed.
Example:

class MyClass {

public:

// Constructor

MyClass() {

// Constructor code

Java
C++ &+ DSA
DSA
// Destructor

~MyClass() {

// Cleanup code

};

int main() {

MyClass obj; // Object created, destructor called when it

goes out of scope

// Object in scope

} // Destructor called when the object goes out of scope

MyClass* dynamicObj = new MyClass(); // Dynamically allocated

object

delete dynamicObj; // Explicit deletion, destructor called

return 0;

Usage:

Resource Release: Handles cleanup tasks like releasing memory, closing files, etc

Automatic Cleanup: Ensures proper cleanup when the object's lifetime ends

Custom Cleanup Logic: Allows custom cleanup operations specific to the class.

Static Members:

Purpose: Belongs to the class itself, not individual objects

Declared with `static`: Applied to variables and methods within the class

Shared Among Objects: Single copy shared by all instances of the class

Accessed via Class Name: Accessed using the class name, not through objects.

Example:

class MyClass {

public:

static int staticVariable; // Declaration of static variable

static void staticMethod() {

// Static method definition

};

int MyClass::staticVariable = 0; // Initialization of static

variable

int main() {

MyClass::staticVariable = 10; // Accessing static variable

MyClass::staticMethod(); // Accessing static method

return 0;

Java
C++ &+ DSA
DSA
Usage:

Shared Data: Store data shared among all instances

Utility Functions: Implement operations not tied to object-specific data

Counters, Constants: Ideal for counters, constants, or global data related to the class.

Static members provide shared attributes and functionalities associated directly with the class, facilitating

shared data and behavior across all instances.

Shallow and deep copy:

Shallow and deep copy are concepts related to copying objects in programming.

Shallow Copy:

Characteristics

Copies each member of the object to the new object

If the object contains pointers, it copies the addresses of the pointed data, not the data itself

Both original and copied objects point to the same memory location for pointer members.

Deep Copy:

Characteristics

Creates a complete replica of the original object

Copies each member and the data pointed to by pointers to new memory locations

Ensures that the original and copied objects have independent memory locations.

Example:

#include <iostream>

#include <cstring>

using namespace std;

class Person {

public:

char* name;

// Constructor

Person(const char* n) {

name = new char[strlen(n) + 1];

strcpy(name, n);

// Destructor

~Person() {

delete[] name;

// Shallow Copy (copy constructor)

Person(const Person& other) {

name = other.name; // Shallow copy: copies the pointer

value

Java
C++ &+ DSA
DSA
// Deep Copy

Person deepCopy(const Person& other) {

name = new char[strlen(other.name) + 1];

strcpy(name, other.name);

};

Usage:

Shallow Copy: Copies pointer values only, leading to multiple objects sharing the same memory

Deep Copy: Creates separate memory for copied objects, ensuring independent copies with their own

memory.

Understanding the difference between shallow and deep copy is crucial when working with objects that contain

pointers, especially for managing memory and preventing unintended side effects.

Initialisation list

class Student {

public :

int rollNumber;

int age;

Student(int r, int a) : rollNumber(r), age(a) {

};

Initialisation list

In C++, initialization lists are used to initialize class member variables when an object of that class is created.

Here's an example using an initialization list in the `Student` class:

class Student {

public :

int rollNumber;

int age;

// Constructor using initiali zation lis t

Student(int r, int a) : rollNumber(r), age(a) {

// Constructor body

};

In this example:

The `Student` class has two member variables: `rollNumber` and `age`

The constructor `Student(int r, int a)` initializes these variables using an initialization list `: rollNumber(r),

age(a)`

Inside the constructor, `rollNumber` is initialized with the value of `r`, and `age` is initialized with the value of `a`.

Java
C++ &+ DSA
DSA
Using initialization lists in constructors is a more efficient way to initialize class member variables, especially for

complex objects or when performing initialization for objects that don't have default constructors. It allows for

direct initialization and can lead to improved performance.

Function Overloading:

Function overloading in C++ allows creating multiple functions with the same name but different parameters

within the same scope.

Characteristics:

Same Function Name: Functions share the same name

Different Parameters: Vary in the number or types of parameters

Return Type: Overloaded functions can have the same or different return types.

Example:

#include <iostream>

using namespace std;

// Function to calculate area of a square

int calculateArea(int sideLength) {

return sideLength * sideLength;

// Overloaded function to calculate area of a rectangle

int calculateArea(int length, int width) {

return length * width;

// Overloaded function with a different parameter type

double calculateArea(double radius) {

return 3.14 * radius * radius;

int main() {

int squareArea = calculateArea(5); // Calls

calculateArea(int)

int rectangleArea = calculateArea(4, 6); // Calls

calculateArea(int, int)

double circleArea = calculateArea(3.5); // Calls

calculateArea(double)

return 0;

Usage:

Different Parameters: Functions with the same name but different parameters improve code readability

Functionality Extension: Allows a single function name to perform different tasks based on provided

parameters

Avoids Name Clashes: Simplifies function naming and organization.

Java
C++ &+ DSA
DSA
Function overloading enables the creation of functions with the same name but different parameters,
facilitating code organization and enhancing flexibility in function usage within a program.

Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class, known as the
derived or child class, inherits properties and behaviors from an existing class called the base or parent class.

Single Inheritance: A derived class inherits from a single base class.


Multiple Inheritance: A derived class inherits from multiple base classes.
Multi-level Inheritance: Derived classes are formed from other derived classes, creating a chain or hierarchy.
Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
Hybrid Inheritance: Combination of different types of inheritance within a class structure.

Code:

#include <iostream>

using namespace std;

// Single Inheritance

class Base {

public:

void displayBase() {

cout << "Base class display" << endl;

};

class DerivedSingle : public Base {

public:

void show() {

cout << "Derived class show" << endl;

};

// Multiple Inheritance

class Base1 {

public:

void display1() {

cout << "Base1 display" << endl;

};

class Base2 {

public:

void display2() {

cout << "Base2 display" << endl;

};

C++ &+ DSA


Java DSA
class DerivedMultiple : public Base1, public Base2 {

public:

void show() {

cout << "Derived class show" << endl;

};

// Multi-level Inheritance

class Derived1 : public Base {

public:

void displayDerived1() {

cout << "Derived1 class display" << endl;

};

class DerivedMultiLevel : public Derived1 {

public:

void displayMultiLevel() {

cout << "DerivedMultiLevel class display" << endl;

};

// Hierarchical Inheritance

class Derived2 : public Base {

public:

void displayDerived2() {

cout << "Derived2 class display" << endl;

};

// Hybrid Inheritance

class DerivedHybrid : public Base1, public Base2 {

public:

void show() {

cout << "Derived class show" << endl;

};

int main() {

DerivedSingle objSingle;

objSingle.displayBase();

objSingle.show();

DerivedMultiple objMultiple;

objMultiple.display1();

objMultiple.display2();

objMultiple.show();

DerivedMultiLevel objMultiLevel;

objMultiLevel.displayBase();

objMultiLevel.displayDerived1();

Java
C++ &+ DSA
DSA
objMultiLevel.displayMultiLevel();

Derived2 objDerived2;

objDerived2.displayBase();

objDerived2.displayDerived2();

DerivedHybrid objHybrid;

objHybrid.display1();

objHybrid.display2();

objHybrid.show();

return 0;

Diamond Problem
The Diamond Problem is a classic issue in multiple inheritance where ambiguity arises due to the presence of
two instances of a common base class within a complex inheritance hierarchy. 

B derives A, C derives A

and D derives B+C.

Now D has 2 instances of A, causing ambiguity while accessing A's properties or methods.

This situation results in ambiguity when the class D tries to access the members inherited from class A, as it has
two paths to reach class A's members, through B and C. Resolving this ambiguity often requires explicit scoping
or virtual inheritance to ensure a single instance of the shared base class A. Virtual inheritance helps avoid
duplicate instances of the base class within the hierarchy, ensuring that there's only one instance of A in the
derived class D.

#include <iostream>

using namespace std;

// Base class A

class A {

public:

void display() {

cout << "Inside class A" << endl;

};

// Derived class B inherits A

class B : public A {};

// Derived class C inherits A

class C : public A {};

// Derived class D inherits both B and C

class D : public B, public C {};

Java
C++ &+ DSA
DSA
int main() {

D obj;

// Ambiguity: D has two instances of class A

// obj.display(); // This line would cause an ambiguity error

obj.B::display(); // Specifying which base class's method to


call

obj.C::display(); // Specifying another base class's method


to call

return 0;

Function Overriding:
When a function of base class is redefined in it’s derived class thereby replacing the base class's
implementation with its own, it’s called function overriding.
Accessing through Scope Resolution Operator:

#include <iostream>

using namespace std;

// Base class

class Base {

public:

void display() {

cout << "Inside Base class" << endl;

};

// Derived class overriding the display() function of Base class

class Derived : public Base {

public:

void display() {

cout << "Inside Derived class" << endl;

};

int main() {

Derived obj;

obj.display(); // Calls Derived class's display() function

// Accessing Base class's display() function using Scope


Resolution Operator

obj.Base::display();

return 0;

Java
C++ &+ DSA
DSA
In this code:
`obj.display()` calls the overridden `display()` function in the `Derived` class
`obj.Base::display()` explicitly calls the `display()` function from the `Base` class using the Scope Resolution
Operator.

Accessing through Pointer:

#include <iostream>

using namespace std;

// Base class

class Base {

public:

void display() {

cout << "Inside Base class" << endl;

};

// Derived class overriding the display() function of Base class

class Derived : public Base {

public:

void display() {

cout << "Inside Derived class" << endl;

};

int main() {

Derived obj;

Base *ptr = &obj;

ptr->display(); // Calls Derived class's display() function

return 0;

In this code:
`ptr->display()` through a pointer of type `Base` to an object of type `Derived` invokes the overridden
`display()` function in the `Derived` class.
Function overriding allows the derived class to provide a specific implementation for a function defined in the
base class, enabling polymorphic behavior in C++.
Virtual Functions:
Virtual functions make sure the correct function is called for an object, regardless of the pointer used for calling
it.

virtual functions in C++ enable polymorphic behavior by allowing the correct function to be called for an object,
regardless of the pointer used for the call. Here's an example illustrating virtual functions:

Java
C++ &+ DSA
DSA
#include <iostream>

using namespace std;

// Base class with a virtual function

class Base {

public:

// Virtual function

virtual void display() {

cout << "Inside Base class" << endl;

};

// Derived class overriding the virtual function

class Derived : public Base {

public:

// Override of virtual function

void display() override {

cout << "Inside Derived class" << endl;

};

int main() {

Base *ptrBase = new Base();

Base *ptrDerived = new Derived();

ptrBase->display(); // Calls Base class's display() function

ptrDerived->display(); // Calls Derived class's display()


function

delete ptrBase;

delete ptrDerived;

return 0;

In this code:
`display()` is a virtual function in the `Base` class
The `Derived` class overrides the `display()` function
Both `ptrBase` and `ptrDerived`, although of type `Base`, call the correct overridden `display()` function based
on the actual object they point to. This behavior is achieved due to the function being declared as virtual.
Virtual functions ensure that the correct function is called based on the actual object being pointed to, enabling
polymorphic behavior and supporting dynamic binding, which happens at runtime.
Abstract Class:
An abstract class in C++ is a blueprint that cannot be instantiated directly, often containing one or more pure
virtual functions. It's designed to be inherited by other classes, which must provide implementations for its pure
virtual functions.

Java
C++ &+ DSA
DSA
Key Points:
Cannot be instantiated: Abstract classes cannot create objects directly
May contain pure virtual functions: Functions declared as pure virtual (`virtual void func() = 0;`) make the
class abstract
Provides an interface: Serves as a template for derived classes to inherit and implement.
Example:

#include <iostream>

using namespace std;

// Abstract class

class Shape {

public:

virtual void draw() = 0; // Pure virtual function

};

// Derived class implementing the abstract class

class Circle : public Shape {

public:

void draw() override {

cout << "Drawing circle..." << endl;

};

int main() {

Circle circle; // Objects can be created from derived classes

circle.draw(); // Invokes the overridden function in Circle

return 0;

`Shape` is an abstract class with a pure virtual function `draw()`


`Circle` inherits from `Shape` and provides an implementation for `draw()`
Objects of the `Circle` class can be created and its overridden `draw()` method is invoked.

Operator overloading:
Operator overloading in C++ enables custom classes to define how standard operators behave when applied
to objects of those classes.
Key Points:
Syntax: `returnType operator symbol(parameters) { /* implementation */ }
Operators Overloaded: Arithmetic, Assignment, Comparison, Increment/Decrement, Logical, Bitwise, etc
Member vs. Non-member Overloading: Operators can be overloaded as member functions or global
functions
Example: Overloading `+` operator for a `Point` class to perform addition.

Java
C++ &+ DSA
DSA
Example:
Code:

#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

Point(int x = 0, int y = 0) : x(x), y(y) {}

Point operator+(const Point &other) {

Point temp;

temp.x = x + other.x;

temp.y = y + other.y;

return temp;

};

int main() {

Point p1(2, 3);

Point p2(4, 5);

Point p3 = p1 + p2; // Operator '+' overloaded for Point


objects

return 0;

`operator+` is overloaded for the `Point` class, allowing `+` to add two `Point` objects
`p1 + p2` uses the overloaded `+` operator for `Point` objects, performing the specified addition operation.

Const Keyword:
In Object-Oriented Programming (OOP), `const` is used to ensure object integrity, define immutability, and
enforce certain behaviors within classes.

Usage in OOP:
1. Const Member Functions:
Guarantee that member functions don't modify object state
Promote const-correctness and prevent unintended changes.

Java
C++ &+ DSA
DSA
class Circle {

public:

double getRadius() const {

// Const member function: Doesn't modify object's


state

return radius;

};

2. Const Objects:
Define objects that can't be modified after initialization
Ensure object's state remains unchanged.
const Circle smallCircle(5.0); // Const object
3. Const References and Pointers:
Pass arameters to functions ithout allo ing modifications
p w w

Ensure ointers don't change the ointed data.


p p

void displayCircle(const Circle& c) {

// Display circle properties without modifying it

4. Mutable Keyword:
A llo s modification of s ecific data members ithin a const member function
w p w ` `

U seful for cases here some members need modification des ite the function being const .
w p ` `

class Rectangle {

private:

mutable double length; // Can be modified even in const


member functions

};

Example:

class Circle {

public:

double getArea() const {

// Const member function: Doesn't modify object's state

return PI * radius * radius;

};

`const usage in
` ensures object immutabilit maintains const correctness and defines beha iors that
OOP y, - , v

p re ent unintended modifications ensuring object integrit ithin classes.


v , y w

Java
C++ &+ DSA
DSA
Q. Predict the output

class Student {

public :

const int rollNumber;

int age;

Student(int r, int a) : rollNumber(r), age(a) {

};

int main() {

Student s1(100, 23);

cout << s1.rollNumber << " " << s1.age;

Ans: 100 23

It will print the values of roll number (which is initialized with 100) and age (initialized with 23) for the Student
object s1.

Friend Function:
Not a Member Function: Defined outside the class, but declared inside using the `friend` keyword
Access to Private Members: Granted access to private and protected members of the class it's declared as a
friend
Usage: Useful for providing specific functions access to private class details without being a member.
Example:

#include <iostream>

using namespace std;

class MyClass {

private:

int secretData;

public:

friend void displaySecret(const MyClass &obj);

};

void displaySecret(const MyClass &obj) {

cout << "Secret data: " << obj.secretData << endl;

int main() {

MyClass obj;

displaySecret(obj); // Accessing private member via friend


function

return 0;

Java
C++ &+ DSA
DSA
`displaySecret()` is a friend function of `MyClass`, accessing the private member `secretData`
The `friend` keyword allows the function access to the private members of `MyClass`.

Q. Predict the Output

class Student {

public :

int rollNumber;

int age;

};

int main() {

Student s1;

Student s2 = s1;

s1.rollNumber = 101;

s1.age = 20;

cout << s2.rollNumber << " " << s2.age;

Ans: 0 0

Explanation: Since s2 is created using the default copy constructor before any modifications are made to s1, it
will contain the default values (zero-initialized) for rollNumber and age. Therefore, s2.rollNumber and s2.age will
both be 0.

Q. Predict the output

class Student {

public :

int rollNumber;

static int getRollNumber() {

return rollNumber;

};

int main() {

Student s;

s.rollNumber = 101;

cout << s.getRollNumber() << endl;

Ans: Compilation Error

Explanation: The code won't compile due to the attempt to access a non-static member (`rollNumber`) from a
static member function (`getRollNumber()`), which isn't allowed in C++. Static member functions can't directly
access non-static members.

Java
C++ &+ DSA
DSA
Q. Create a class ‘person’ having attributes as age and weight. Access its object using pointers.
Code:

class Person {

public:

int age;

double weight;

};

int main() {

Person person;

person.age = 25;

person.weight = 65.5;

// Accessing object using pointers

Person *ptrPerson = &person;

cout << "Age: " << ptrPerson->age << endl;

cout << "Weight: " << ptrPerson->weight << endl;

return 0;

The Person class has attributes age and weight.

In main(), an object of Person class named person is created and its attributes (age and weight) are assigned
values.

A pointer ptrPerson of type Person is initialized to the address of the person object.

The arrow operator (->) is used to access the members of the object person through the pointer ptrPerson,
displaying its age and weight

Q. maruti.engine.bolts = 25 ;
Which of the following is True? 

1. Class bolts is nested within class engine 

2. Class engine is nested within class maruti 

3. Class maruti is nested within class engine 

4. Class maruti is nested within class bolts

Ans: 2.Class engine is nested within class maruti

Solution: The statement maruti.engine.bolts = 25; indicates that engine is a member of maruti, and within
engine, there exists a member named bolts.

So this tell bolts is just an int not a class, and maruti and engine are class, and engine class in nested in maruti
class.

Q. Predict the output

Java
C++ &+ DSA
DSA
#include <iostream>

using namespace std;

class Shape{

public : 

int height;

int width;

};

int main() {

Shape *s = new Shape();

s -> height = 1;

cout << s -> height;

Ans: 1

s -> height = 1; sets the height attribute of the dynamically allocated Shape object to 1.

cout << s -> height; prints the value of height, which is 1.

Q. Choose the appropriate option

The member in class by default are

Protecte
Stati
Publi
Private

Ans: Private
Explanation: Members without an explicit access specifier (public, protected, or private) are private.

Q. Choose the appropriate option

Objects are the variables of the type ____?

Strin
Boolea
Clas
All data types can be included
Ans: Class, In object-oriented programming, objects are instances of classes.

Q. Choose the appropriate option

Which functions are declared inside a class have to be defined separately outside the class?
Static function
Const function
Inline function
Member functions

Java
C++ &+ DSA
DSA
Answer: D) Member functions

Member functions declared inside a class have to be defined separately outside the class. They are much like
normal functions.

Q. Choose the appropriate option

Which one of the following is the demerit of procedure-oriented languages?

A procedure-oriented language does not model real-world problem


In procedure-oriented Language message parsing is difficul
A procedure-oriented Language works slowl
In procedure-oriented Language, it is difficult to apply the inheritance concept
Ans: A procedure-oriented language does not model real-world problems
Explanation: A procedure-oriented language does not model real-world problems because functions are
action-oriented.

Q. An object cannot invoke a private function using the dot operator.


Tru
False
Ans: A) True
Explanation: An object cannot invoke a private function using the dot operator as it does not have access.

Q. Predict the output

#include <iostream>

using namespace std;

class Student{

public :

char *name;

int rollNo;

Student(int num){

rollNo = num;

void print(){

cout<<rollNo;

};

int main() {

Student s(12);

s.print();

Ans: 12
Explanation: s(12) initializes the rollNo member of the s object with the value 12,s.print(); invokes the print()
function, which outputs the value of rollNo, resulting in the output of 12.

Java
C++ &+ DSA
DSA
Q. Choose the appropriate option

The functions go in the _______ section of a class definition

Declaratio
Implementatio
Prototyp
Functioning
Ans: Implementation
Explanation: Functions go in the Implementation section of a class to provide the actual code defining their
behavior and operations on the class's data members.
Q. When a program is executed, the ____ interacted by sending a message to one another.
Object
Classe
Operating syste
Memory
Ans: 1) Objects
Explanation: When a program is executed, the objects interact by sending a message to one another. For
example, if "customer" and "account" are two objects in a program, then the customer object may send a
message to the account object requesting the back balance.

Q. Object-oriented languages follow which approach?


Top-down approac
Bottom-up approach
Ans: 2) Bottom-up approach
Explanation: A procedure-oriented language follows a Top-down approach whereas object-oriented
programming languages follow a bottom-up approach.

Q. A non-member function cannot access which data of the class?


Private dat
Public dat
Protected dat
All of the above

Ans: 1) Private data


Explanation: A member function can access private data of the class but a non-member function cannot do
that.

Java
C++ &+ DSA
DSA
THANK

YOU !

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy