Oopc++ Question Bank
Oopc++ Question Bank
COMPUTER ENGINEERING
DEPARTMENT
QUESTION BANK
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)
QUESTION BANK
UNIT-1
PRINCIPLES OF OBJECT ORIENTED PROGRAMMIG
1. What is Object Oriented Programming Language?
2. List out the applications of Object Oriented Programming in detail.
3. Explain the principles of Object oriented programming language.
4. Explain advantages and disadvantages of Object Oriented Programming.
5. Explain structure of C++ with example.
6. Describe all datatypes used in C++.
7. How we can declare variable in C++?Explain with an example.
8. Describe dynamic initialization of variable in C++.
9. Explain reference variable in C++.
10. Explain scope resolution operator.
11. Differentiate OOP & POP.
12. What is the meaning of access specifier? Explain it with example.
UNIT-2
FUNCTIONS,CLASS AND OBJECTS
1. Define function with function prototype, function declaration & function calling.
2. Define an inline function & Explain How to implement an inline function with example.
3. Explain default and constant arguments with example.
4. Explain Function Overloading with example.
5. Define class & object.
6. Define Member Function & Nesting of Member Function.
7. Define Private Member Function.
8. What is Friend Function? Explain with example.
9. WAP using friend function to find maximum number between two numbers, two numbers are
the private data of two different class.
10. WAP which illustrate the use of object and class concept using to show student’s detail as output.
UNIT-3
CONSTRUCTOR AND DECONSTRUCTOR
1. What is constructor? Explain in brief with example.
2. Explain default constructor with program.
3. How to use a copy constructor? Justify with program.
4. Explain parameterized constructor with example.
5. Differentiate Constructor & Destructor.
6. What is Destructor? Give example.
7. Write a C++ Program to enter student details by Passing parameters to constructors.
8. Write a C++ program to perform operator overloading using constructor.
UNIT-4
INHERITANCE
1. Explain Inheritance in C++ and also list out its types.
2. What are derived classes in C++?
3. Explain Single Inheritance with an example.
4. What is Multiple Inheritance? Explain it with an example.
5. What is Multilevel Inheritance? Explain it with an example.
6. What is Hybrid Inheritance? Explain it with an example.
7. What is Function Overriding in C++?Explain it with example.
8. Differentiate between Function Overloading and Function Overriding.
9. What is a Virtual Base Class? Explain it with an example.
10. Explain Abstract Classes in C++.
UNIT-5
POINTERS & VIRTUAL FUNCTIONS
1. Explain Pointers to Objects in C++.
2. How do you declare and initialize a pointer to an object in C++?
3. What is a Pointer to a Derived Class in C++?
4. Define Virtual Functions in C++.
5. Explain the concept of Pointer to Virtual Functions in C++.
6. What is the 'this' Pointer in C++?
7. What is the difference between a virtual function and a non-virtual function?
ANSWERS
UNIT-1
PRINCIPLES OF OBJECT ORIENTED PROGRAMMIG
Benefits of OOP
Modular, scalable, extensible, reusable, and maintainable.
It models the complex problem in a simple structure.
Object can be used across the program.
Code can be reused.
We can easily modify, append code without affecting the other code blocs.
Provides security through encapsulation and data hiding features.
Beneficial to collaborative development in which a large project is divided into groups.
Debugging is easy.
Limitations of OOP
Solving problems takes more time as compared to Procedure Oriented Programming.
The size of the programs created using this approach may become larger than the programs
written using the procedure-oriented programming approach.
OOP code is difficult to understand if you do not have the corresponding class documentation.
In certain scenarios, these programs can consume a large amount of memory.
Not suitable for small problems.
Takes more time to solve problems.
Graphical User Interface (GUI) Development: OOP is well-suited for creating GUI
applications because it allows developers to represent GUI components (such as buttons,
windows, and menus) as objects. Frameworks like Java Swing, JavaFX, Qt (C++), and Tkinter
(Python) leverage OOP principles for GUI development.
PIET -DS(CE) PAGE NO:4
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)
Game Development: Many game development frameworks and engines, such as Unity (C#),
Unreal Engine (C++), and Godot Engine (GDScript), are based on OOP principles. OOP
facilitates the creation of game objects, characters, environments, and interactions, making it
easier to manage complex game logic.
Artificial Intelligence and Machine Learning: OOP is applied in building AI and ML systems,
including machine learning models, neural networks, and intelligent agents. OOP facilitates the
organization of code into reusable components, making it easier to develop and maintain complex
AI algorithms.
Internet of Things (IoT): OOP is used in IoT development to model and control interconnected
devices and sensors. Object-oriented languages like Python and C++ are commonly used for IoT
programming, enabling developers to create modular and scalable IoT applications.
Financial and Banking Systems: OOP is employed in developing financial software, banking
systems, and trading platforms. OOP principles such as encapsulation, inheritance, and
polymorphism help in modeling financial instruments, transactions, and business logic.
E-commerce and Content Management Systems: OOP is widely used in building e-commerce
platforms, content management systems (CMS), and online marketplaces. OOP facilitates the
creation of reusable components for managing products, orders, users, and content.
Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an
instance of the class.
It contains member functions, variables that we have defined in the class.
It occupies space in the memory. Different objects have different states or attributes, and
behaviors.
Class
A class is a blueprint or template of an object. It is a user-defined data type. Inside a class, we
define variables, constants, member functions, and other functionality.
It binds data and functions together in a single unit. It does not consume memory at run time.
Classes are not considered as a data structure.
It is a logical entity. It is the best example of data binding. Note that a class can exist without an
object but vice-versa is not possible.
Encapsulation:
Encapsulation means bundling the data (properties) and methods (functions) that operate on the
data into a single unit called an object.
This allows for the hiding of internal implementation details and providing a controlled interface
for interacting with the object.
Encapsulation helps in achieving data security, as access to the object's data can be restricted to
only the necessary methods.
Inheritance:
Inheritance allows a new class (subclass or derived class) to inherit properties and methods from
an existing class (superclass or base class).
This promotes code reuse and establishes a hierarchical relationship between classes. Subclasses
can extend or modify the behavior of the superclass, leading to more modular and extensible code.
Polymorphism:
Polymorphism refers to the ability of objects to take on different forms or behaviors based on the
context in which they are used.
There are two types of polymorphism: compile-time polymorphism (method overloading) and
runtime polymorphism (method overriding).
Polymorphism enables code flexibility and extensibility by allowing objects of different classes
to be treated uniformly through a common interface.
Abstraction:
Abstraction involves focusing on essential properties and behaviors while hiding unnecessary
implementation details.
It allows developers to create models that represent real-world entities in a simplified manner.
Abstraction helps in managing complexity by providing a clear and concise interface for
interacting with objects, thereby enhancing code readability and maintainability.
Advantages:
Modularity: OOP promotes modularity by breaking down complex systems into smaller,
manageable modules (objects). This makes it easier to understand, maintain, and update the
codebase, as changes made to one part of the system are less likely to affect other parts.
Reusability: OOP encourages code reuse through inheritance and composition. Objects and
classes can be reused in different parts of the program or even in entirely different programs,
reducing redundancy and promoting code efficiency.
Scalability: OOP supports scalability by allowing developers to extend existing classes to create
new ones with additional features or behaviors. This facilitates building upon existing code rather
than starting from scratch, making it easier to accommodate changes and add new functionality
as the project grows.
Maintainability: OOP promotes code maintainability through encapsulation, inheritance, and
abstraction. Encapsulation hides internal implementation details, inheritance facilitates code
reuse, and abstraction focuses on essential properties and behaviors, making it easier to
understand and modify the code over time.
Flexibility and Extensibility: OOP enables code flexibility and extensibility through
polymorphism. Polymorphism allows objects of different classes to be treated uniformly through
a common interface, enabling developers to write more flexible and adaptable code that can
accommodate changes and variations in requirements.
Disadvantages:
Complexity: OOP can introduce complexity, especially for beginners or when used
inappropriately. Understanding the relationships between classes, managing inheritance
hierarchies, and designing effective class structures require careful planning and can be
challenging in large-scale projects.
Overhead: OOP can introduce overhead in terms of memory and processing resources. Objects
and classes consume memory, and dynamic dispatch mechanisms used for method calls can incur
performance overhead compared to procedural programming approaches.
Learning Curve: OOP has a steep learning curve for beginners due to its abstract concepts and
terminology. Understanding concepts such as inheritance, polymorphism, and object
relationships requires time and practice, making it challenging for newcomers to grasp initially.
Performance: In certain scenarios, OOP may not be the most efficient choice in terms of
performance. Dynamic dispatch mechanisms, such as virtual function calls in languages like C++,
can incur runtime overhead, impacting performance in performance-critical applications.
Design Overhead: Designing effective class structures and object relationships requires careful
planning and foresight. Poorly designed class hierarchies or overly complex inheritance structures
can lead to code that is difficult to understand, maintain, and extend over time.
Documentation Section:
This section comes first and is used to document the logic of the program that the programmer
going to code.
It can be also used to write for purpose of the program.
Whatever written in the documentation section is the comment and is not compiled by the
compiler.
Linking Section:
The linking section contains two parts:
1.Header Files:
Generally, a program includes various programming elements like built-in functions, classes,
keywords, constants, operators, etc. that are already defined in the standard C++ library.
In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
Standard headers are specified in a program through the preprocessor directive #include. In
Figure, the iostream.h header is used. When the compiler processes the instruction
#include<iostream.h>, it includes the contents of the stream in the program. This enables the
programmer to use standard input, output, and error facilities that are provided only through
the standard streams defined in <iostream.h>. These standard streams process data as a stream
of characters, that is, data is read and displayed in a continuous flow. The standard streams
defined in <iostream.h> are listed here.
#include<iostream.h>
2.Namespaces:
A namespace permits grouping of various entities like classes, objects, functions, and various
C++ tokens, etc. under a single name.
Any user can create separate namespaces of its own and can use them in any other program.
In the below snippets, namespace std contains declarations for cout, cin, endl, etc. statements.
Namespaces can be accessed in multiple ways:
Definition Section:
It is used to declare some constants and assign them some value.
In this section, anyone can define your own datatype using primitive data types.
It uses #define keyword to declare constants in C++
prototype in this section for the function which for you are going to write code after the main
function.
Main Function:
The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
All the statements that are to be executed are written in the main function.
The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
Once all instructions from the main function are executed, control comes out of the main
function and the program terminates and no further execution occur.
// Preprocessor directives
#include <iostream.h> // Include the standard input/output stream library
// Global declarations
// Use the standard namespace
// Main function
int main() {
// Statements
cout << "Hello, world!" << endl;
// Function call
greet();
// Function definition
void greet() {
// Function body
cout << "Greetings from the greet() function!" << endl;
}
User
Primitive Derived
defined
Double Floating
Typedef
Point
Void
Wide character
1.Primitive datatype
integer (int)
In order to identify integers, the int keyword is utilized.
Usually, it is 4 bytes in size.
It can therefore store values between -2147483648 and 2147483647.
Example:-int = 344
Character (char)
Characters are referred to by the term char.
It has a 1 byte size.
In C++, characters are encased in single quotes.
Example:- ‘m’
Boolean (bool)
True or false are the only two valid values for the bool data type.
Loops and conditional statements both employ booleans (which we will learn in later chapters).
Example:-bool = ‘true’;
Double
To store floating-point integers with double precision, use the keyword double (including
decimals and exponentials).
The double variable takes up 8 bytes.
Example:-double = 5556.78;
Void
It is argued that anything has no worth if it is empty.
The void data type represents a valueless entity.
The declaration of variables is not permitted for the void type.
It just uses functions and doesn’t return any data.
Example:-void function(void);
2.Derived datatype
Function
A function is a reusable block of code that performs a specific task. It is a derived data type
because you can define functions to work with other data types and can even return values of
different data types.
Arrays:
A collection of elements of the same data type arranged in contiguous memory locations.
Arrays are declared using square brackets [], e.g., int numbers[5];.
Pointers:
Variables that store memory addresses of other variables. Pointers are declared using an
asterisk *, e.g., int* ptr;.
References:
Alias to an existing variable. References are declared using an ampersand &, e.g., int a = 10;
int& ref = a;.
Structures:
A composite data type that groups together variables of different data types under a single
name. Structs are declared using the struct keyword.
Union:
A union is a user-defined data type that allows you to store different data types in the same
memory location. Unlike structures, which allocate memory for all members, unions share
memory among their members.
Enumeration Types:
Enumerations (enum): A user-defined data type used to define named constants. Enumerations
are declared using the enum keyword.
Typedef:
typedef is a keyword that allows you to create aliases for existing data types, making your code
more readable and providing abstraction. It's not a new data type but a way to create alternative
names for existing ones.
datatype variable_name;
Here, datatype must be a valid C++ data type including char, w_char, int, float, double, bool or any
user-defined object, etc., and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here.
int i;
float a=3.72;
1.User Input: You can prompt the user to enter a value, which is then assigned to the variable. This
is commonly done using input/output stream functions like std::cin.
Example:
#include <iostream.h>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}
2.Function Calls:
We can initialize variables using values returned by functions. This allows for more complex
initialization logic to be encapsulated within functions.
Example:
#include <iostream.h>
int getUserInput() {
int input;
std::cout << "Enter a number: ";
std::cin >> input;
return input;
}
int main() {
int number = getUserInput();
std::cout << "You entered: " << number << std::endl;
return 0;
}
Example:
#include <iostream.h>
int main() {
int x = 5;
int y = x * 2; // Dynamic initialization based on expression
cout << "Value of y: " << y << endl;
return 0;
}
4.Conditional Initialization:
We can initialize variables conditionally based on certain criteria or conditions.
Example:
#include <iostream.h>
int main() {
int x;
bool condition = true;
if (condition) {
x = 10;
} else {
x = 20;
}
cout << "Value of x: " << x << endl;
return 0;
}
Dynamic initialization allows for greater flexibility and adaptability in C++ programs, enabling
variables to be initialized based on runtime conditions or user input. This can be useful in scenarios
where the initial value of a variable is not known until the program is executed.
Example::
#include <iostream.h>
int main() {
int originalVariable = 62;
// Declaration of reference variable
int& referenceVariable = originalVariable;
cout << "Original variable value: " << originalVariable << std::endl;
cout << "Reference variable value: " << referenceVariable << std::endl;
Output:
Example
#include <iostream.h>
char a = 'm';
static int b = 50;
int main() {
char a = 's';
cout << "The static variable : "<< ::b;
cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a;
return 0;
}
Output:
Public:
The public access specifier is used to specify that a class member can be accessed from
anywhere, both inside and outside the class.
This means that any function or object can access the public members of the class.
The public members of a class are typically used to represent the interface of the class.
Private:
The private access specifier is used to specify that a class member can only be accessed from
Protected:
The protected access specifier is used to specify that a class member can be accessed from
within the class and its derived classes.
This means that any function or object outside the class hierarchy cannot access the protected
members of the class.
The protected members of a class are typically used to represent the implementation of a class
that should be accessible to its derived classes.
UNIT-2
FUNCTIONS, CLASS AND OBJECTS
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
Syntax :
return_type function_name( parameter list );
Example:
int sum(int, int );
Calling or invoking the function locates the function in the memory, furnishing it with arguments
and causing it to execute. When a function is called then the control passed to the function where
it is actually defined.
Syntax :
variable= function_name(arg1,arg2,…,argn);
Example:
result= sum(num1, num2);
2. Define an inline function & Explain How to implement an inline function with
example.
Answer:
An inline function is a function that is expanded in line when it is called. When the inline function
is called whole code of the inline function gets inserted or substituted at the point of the inline
function call.
This substitution is performed by the C++ compiler at compile time. An inline function may
increase efficiency if it is small.
Syntax :
inline return-type function-name(parameters)
{
// function code
}
If a function member is defined entirely in the class specification body (typically in .h header file)
then, it is considered as an in-line function.
Example::
#include <iostream.h>
inline int cube(int s)
{
return s * s * s;
}
int main()
{
cout << "The cube of 2 is: " << cube(2) << "\n";
return 0;
}
Output:
Example::
#include<iostream.h>
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 20)<<"\n";
cout << sum(10, 20,30)<<"\n";
cout << sum(10, 20,30, 50)<<"\n";
return 0;
}
Output:
Constant arguments:
The constant argument turns out to be most useful when the calling of the functions takes place
by reference.
A constant argument is the one whose modification cannot take place by the function.
Furthermore, in order to make an argument constant to a function, the use of a keyword const can
take place like- int sum (const int a, const int b).
Example::
#include<iostream.h>
int main()
{
int a = 5;
double b = 10.5;
// Call the function with constant arguments
printValues(a, b);
return 0;
}
Output:
Example:
#include<iostream.h>
// Function to add two integers
int add(int a, int b)
{
return a + b;
}
int main() {
// Call the overloaded functions
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl;
cout << "Sum of 2.5 and 3.7: " << add(2.5, 3.7) << endl;
return 0;
}
Output:
};
Example:
class Room
{
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return length * breadth * height;
}
};
Object:
An object is a single instance of a class.When a class is defined, only the specification for the
object is defined; no memory or storage is allocated.
To use the data and access functions defined in the class, we need to create objects.
Syntax :
className objectVariableName;
Ex:
void sampleFunction()
{
Room room1, room2;
}
int main()
{
Room room3, room4;
}
Example:
#include <iostream.h>
class average
{
int a,b;
public:
void read();
void print();
int avg();
};
void average::read()
{
cout<<"\n enter a and b: ";
cin>>a>>b;
}
void average::print()
{
cout<<"value of a: "<<a;
cout <<"\nvalue of b: "<<b;
cout<<"\naverage is : "<<avg();
}
int average::avg()
{
return (a+b)/2; }
main() {
average A;
A.read();
A.print(); }
Output:
Example:
#include <iostream.h.h>
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length; }
int main()
{
Box b;
cout <<"Length of box: "<< printLength(b)<<std::endl;
return 0;
}
Output:
9. WAP using friend function to find maximum number between two numbers,
two numbers are the private data of two different class.
Answer:
Example:
#include <iostream.h>
// Forward declaration of second class
class SecondClass;
int main() {
FirstClass first(10);
SecondClass second(20);
cout << "Maximum number is: " << findMax(first, second) << std::endl;
return 0;
}
Output:
10.WAP which illustrate the use of object and class concept using to show
student’s detail as output.
Answer:
#include <iostream.h>
PIET -DS(CE) PAGE NO:25
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)
#include <conio.h>
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};
int main()
{
student std; //object creation
std.getDetails();
std.putDetails();
return 0;
}
Output:
UNIT-3
CONSTRUCTOR AND DESTRUCTOR
Example:
#include <iostream.h>
class Person {
string name;
int age;
public:
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1("abc ", 30);
person1.display();
return 0;
}
Output:
Example:
#include <iostream.h>
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
Example:
#include <iostream.h>
#include<conio.h>
class A
{
public:
int x;
Output:
Example:
#include <iostream.h>
#include<conio.h>
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Meera", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
Example:
#include<iostream.h>
#include<conio.h>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Output:
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Student e1 =Student(101, "Sonoo", 890000); //creating an object of Employee
Student e2=Student(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
class Arithmetic {
private:
int value;
public:
// Constructor
Arithmetic(int val = 0) {
value = val;
}
int main() {
Arithmetic a(10);
Arithmetic b(5);
// Addition
Arithmetic addition = a + b;
cout << "Addition: ";
addition.display();
// Subtraction
Arithmetic subtraction = a - b;
cout << "Subtraction: ";
subtraction.display();
// Multiplication
Arithmetic multiplication = a * b;
cout << "Multiplication: ";
multiplication.display();
// Division
Arithmetic division = a / b;
cout << "Division: ";
division.display();
return 0;
}
Output:
UNIT-4
INHERITANCE
Inheritance promotes code reuse, extensibility, and modularity by allowing the derived class to inherit
and extend the functionality of the base class.
Derived Class (Subclass): The derived class is the new class that inherits properties and
behaviors from the base class. It extends or modifies the functionality of the base class by
adding new members or overriding existing ones.
Example:
class BaseClass {
// Base class members
};
Syntax:
class BaseClass
{
// Base class members
};
Code:
#include <iostream.h>
#include<conio.h>
// Driver Code
int main()
{
// Initialise a Derived class geeks
Derived cpp;
Output:
Example:
#include <iostream.h>
class Base {
public:
void display() {
cout <<"This is the Base class" << endl;
}
};
int main() {
Derived d;
d.display(); // Accessing Base class function
d.show(); // Accessing Derived class function
return 0;
}
Output:
Syntax:
class A
{
... .. ...
};
class B
{
... .. ...
};
Example:
#include<iostream.h>
#include<conio.h>
/* create a child_class to inherit features of Base_class and Base_class2 with access specifier. */
class child_class: public Base_class, public Base_class2
{
// access specifier
public:
void display3() // It is a member function of derive class
{
cout << " It is the function of the derived class " << endl;
}
};
PIET -DS(CE) PAGE NO:40
OBJECT ORIENTED PROGRAMMING WITH C++ (03606213)
int main ()
{
// create an object for derived class
child_class cc;
cc.display(); // call member function of Base_class1
cc.display2(); // call member function of Base_class2
cc.display3(); // call member function of child_class
}
Output:
Syntax:
class A // base class
{
...........
};
class B : access_specifier A // derived class
{
...........
};
class C : access_specifier B // derived from derived class B
{
...........
};
Example:
#include<iostream.h>
#include<conio.h>
class Grandfather
{
public:
void Print1()
{
cout<<"Process of Grandfather Class.\n";
}
};
class Father: public Grandfather
{
public:
void Print2()
{
cout<<"Process of Father Class.\n";
}
};
class Son: public Father
{
public:
void Print3()
{
cout<<"Process of Son Class.\n";
}
};
int main()
{
Son obj;
obj.Print1();
obj.Print2();
obj.Print3();
return 0;
}
Output:
In hybrid inheritance, one or more base classes are inherited virtually, which means that only one
instance of the virtual base class is created in the derived class hierarchy, ensuring that there are no
duplicate instances of the virtual base class.
Syntax:
Class A
{
statement(s)
}:
Class B: public A
{
statement(s);
};
Class C
{
statement(s);
};
Class D: public B, public C
{
statement(s);
};
Example:
#include<iostream.h>
#include<conio.h>
class A
{
public:
int a;
};
class C
{
public:
int c;
C()
{
c = 14; //initialise c
}
};
int main()
{
D obj1;
obj1.sum();
}
Output:
Example:
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class";
}
};
class B:public A
{
public:
void display()
{
cout<<"Derived Class";
}
};
int main()
{
B obj;
obj.display();
return 0;
}
Output:
Function overriding is particularly useful for implementing polymorphism, where objects of different
classes can be treated as objects of the same base class type, allowing for dynamic method dispatch
at runtime based on the actual type of the object.
Example:
#include<iostream.h>
#include<conio.h>
class B {
public: int b;
};
int main()
{
D3 obj;
Output:
Example:
#include <iostream.h>
#include<conio.h>
class base_class
{
public:
virtual void display() = 0;
};
int main()
{
derived_class obj;
obj.display();
return 0;
}
Output:
UNIT-5
POINTERS & VIRTUAL FUNCTIONS
Example:
#include <iostream.h>
#include <string.h>
class Person
{
public: string name;
int age;
void say_hello()
{
cout << "Hello, my name is " << name << endl;
}
};
int main()
{
// Create a pointer to a Person object
Person *p = new Person();
// Access the object's properties and methods using the pointer
p->name = "OOP";
p->age = 25;
p->say_hello();
// Deallocate memory when the object is no longer needed delete p;
return 0;
}
Output:
ClassName and returns a pointer to it. The new keyword is used for dynamic memory allocation,
and ClassName() is the constructor call to create the object.
Example:
#include<iostream.h>
#include<conio.h>
class base
{
public:
void show()
{
cout<<"base class";
}
};
class derive: public base
{
public:
void show()
{
cout<<"derive class";
}
};
int main()
{
derive d;
derive *dp;
dp = &d;
dp -> show();
return 0;
}
Output:
Example:
#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void display()
{
cout<<"base class called";
}
};
class B: public A
{
public:
void display()
{
int main()
{
A*a;
B b;
a = &b;
a -> display();
return 0;
}
Output:
Example:
#include <iostream.h>
class base {
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
void show()
{
cout << "show derived class\n";
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
return 0;
}
Output:
Example:
#include <iostream.h>
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Output:
All derived class may or may not redefine All derived class must redefine pure
virtual function of base class. virtual function of base class otherwise
derived class also becomes abstract just
like base class.
Syntax: Syntax:
virtual<func_type><func_name>() virtual<func_type><func_name>()
{ = 0;
// code
}