KEMBAR78
Public - Private - Protected | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
5 views24 pages

Public - Private - Protected

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)
5 views24 pages

Public - Private - Protected

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/ 24

Q. Discuss the use private, public and protected access specifiers in inheritance.

public – members are accessible from outside the class, and members can be
accessed from anywhere.
private – members cannot be accessed (or viewed) from outside the class, i.e
members are private to that class only.
protected – members cannot be accessed from outside the class, but, they can
be accessed in inherited classes or derived classes.

Public Inheritance
In public inheritance, all public members of the base class remain public in the derived class,
and protected members remain protected. However, private members of the base class are
not accessible directly in the derived class. Public inheritance represents an "is-a"
relationship, meaning the derived class is a specialized form of the base class. This type of
inheritance allows objects of the derived class to be used wherever objects of the base class
are required.
Example:
class Animal {
public:
int legs = 4;
protected:
string sound = "Roar";
};
class Dog : public Animal {
void show() {
cout << legs; // Accessible (public stays public)
cout << sound; // Accessible (protected stays protected)
}
};
Key Point:
Public inheritance is used when the derived class should follow the same interface as the
base class while allowing outside access to public members.
Protected Inheritance
In protected inheritance, the public members of the base class become protected in the
derived class, and protected members remain protected. This means the derived class can
access these members, but they are not accessible outside the derived class. The private
members of the base class remain inaccessible, as in public inheritance. Protected
inheritance is useful when the base class functionality should be shared with derived classes
but hidden from the outside world.
Example:
class Animal {
public:
int legs = 4;
protected:
string sound = "Roar";
};
class Cat : protected Animal {
void show() {
cout << legs; // Accessible (public becomes protected)
cout << sound; // Accessible (protected stays protected)
}
};

Key Point:
Protected inheritance is used when you want to provide limited access to base class
members within the derived class hierarchy but restrict it from external access.

Private Inheritance
In private inheritance, both public and protected members of the base class become private
in the derived class. This means they cannot be accessed directly outside the derived class.
Private inheritance represents a "has-a" or "is-implemented-in-terms-of" relationship rather
than an "is-a" relationship. It is used when the derived class needs access to the base class's
functionality internally but should not expose it outside.
Example:
class Animal {
public:
int legs = 4;
protected:
string sound = "Roar";
};
class Bird : private Animal {
void show()
{
cout << legs; // Accessible (public becomes private)
cout << sound; // Accessible (protected becomes private)
}
};

Key Point:
Private inheritance is useful when you want to use the base class’s features within the
derived class but prevent any direct external access.

Q. Describe the features of Object Oriented Programming?


Class.
 The building block of C++ that leads to Object-Oriented programming is a Class.
 A class is a user-defined data type.
 Class is also called as collection of objects.
 It consists of data members and member functions, which can be accessed and used
by creating an instance of that class.
 It represents the set of properties or methods that are common to all objects of one
type.
 A class is like a blueprint for an object.
 For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class,
and wheels, speed limits, mileage are their properties.
Object
 It is a basic unit of Object-Oriented Programming and represents the real-life entities.
 An Object is an instance of a Class.
 When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
 An object has an identity, state, and behavior.
 It binds data and functions together in a single unit.
 Each object contains data and code to manipulate the data.
 Objects can interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and type of response returned by
the objects.
 For Example “Dog” is a real-life Object, which has some characteristics like color,
Breed, Bark, Sleep, and Eats.

Inheritance
 Inheritance is an important pillar of OOP(Object-Oriented Programming).
 When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
 It provides code reusability. It is used to achieve runtime polymorphism.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by a sub-class is called Base Class
or Superclass.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to


create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.

 Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
class Parent {
public:
int age;
};
class Child : public Parent {
public:
void show() { cout << age; }
};
Encapsulation
 Encapsulation is defined as wrapping up data and information under a single unit.
 In Object-Oriented Programming, Encapsulation is defined as binding together the
data and the functions that manipulate them.
 Encapsulation also leads to data abstraction or data hiding. Using encapsulation also
hides the data.
 It restricts direct access to some of the object's components, ensuring better security
and control over data.
 Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the sales-related activities
and keeps records of all the sales. Now there may arise a situation when for some
reason an official from the finance section needs all the data about sales in a
particular month. In this case, he is not allowed to directly access the data of the
sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is.
Here the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.

Data Abstraction
 Data abstraction is one of the most essential and important features of object-
oriented programming in C++.
 Abstraction means displaying only essential information and hiding the details.
 Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
 Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerator will increase the speed of the car or applying brakes will stop the car
but he does not know how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of an accelerator, brakes, etc. in the car. This is what abstraction is.
 Abstraction using Classes: We can implement Abstraction in C++ using classes. The
class helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
 Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever
we need to calculate the power of a number, we simply call the function pow()
present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.
Polymorphism
 Polymorphism is considered one of the important features of Object-Oriented
Programming.
 The word polymorphism means having many forms.
 In simple words, we can define polymorphism as the ability of a message to be
displayed in more than one form.
 It enables code flexibility and reusability.
 A person at the same time can have different characteristics. A man at the same time
is a father, a husband, and an employee. So the same person possesses different
behavior in different situations. This is called polymorphism.
 An operation may exhibit different behaviors in different instances. The behavior
depends upon the types of data used in the operation.
 C++ supports operator overloading and function overloading.

 Operator Overloading: The process of making an operator exhibit different behaviors


in different instances is known as operator overloading.
 Function Overloading: Function overloading is using a single function name to
perform different types of tasks. Polymorphism is extensively used in implementing
inheritance.
 Polymorphism is mainly of two types:
1. Compile-time polymorphism (Static Binding):
o Achieved using function overloading and operator overloading.
o The function to be called is determined at compile time.
2. Run-time polymorphism (Dynamic Binding):
o Achieved using function overriding via inheritance and virtual functions.
o The function to be called is determined at runtime.

Example: Suppose we have to write a function to add some integers, sometimes there
are 2 integers, and sometimes there are 3 integers. We can write the Addition Method
with the same name having different parameters, the concerned method will be called
according to parameters.

Q. Discuss the concept of destructor.


 A destructor in C++ is a special function that runs automatically when an object is
destroyed.
 It is mainly used to free up memory or release resources (like closing files or
disconnecting from networks).
 A destructor is also a special member function like a constructor. Destructor destroys
the class objects created by the constructor.
 Destructor has the same name as their class name preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
 It cannot be declared static or const.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

Q. What is constructor? Discuss its types with example.


 Constructor in C++ is a special method that is invoked(called) automatically at the
time an object of a class is created.
 Its main purpose is to initialize the object's properties or allocate resources for it
 It is used to initialize the data members of new objects generally.
 To create a constructor, use the same name as the class, followed by parentheses ():
 Constructors have the same name as the class and do not have a return type, not
even `void`.
 The constructor in C++ has the same name as the class or structure.
 It constructs the values i.e. provides data for the object which is why it is known as a
constructor.
 When an object is completed, the constructor is called. Because it creates the values
or gives data for the thing, it is known as a constructor.
 Overloaded constructors are possible.
 Declaring a constructor virtual is not permitted.

Types of constructor:-
Default Constructor
 A default constructor is a special type of constructor that gets called
automatically when an object of a class is created.
 It does not take any parameters and is used to initialize the object with
default values.
 It is also called a zero-argument constructor.
 Syntax of Default Constructor
 className() {
// body_of_constructor
}

Parameterized Constructor
 Parameterized Constructors make it possible to pass arguments to constructors.
 Typically, these arguments help initialize an object when it is created.
 To create a parameterized constructor, simply add parameters to it the way you
would to any other function.
 When you define the constructor’s body, use the parameters to initialize the object.
 Syntax of Parameterized Constructor
 className (parameters...) {
// body
}

Copy Constructor
 A copy constructor is a type of constructor that creates an object using another
object of the same class.
 The process of initializing members of an object through a copy constructor is known
as copy initialization.
 It is also called member-wise initialization.
 the copy constructor initializes one object with the existing object, both belonging to
the same class on a member-by-member copy basis.
 A copy constructor is a special constructor in C++ that creates a new object by
copying the values of an existing object.
 It is useful when we need to duplicate an object while preserving its properties.
 It takes an object of the same class as a constant reference (const ClassName &obj).

 The parameter is passed by reference (&) to avoid infinite recursion.


 const keyword ensures that the original object remains unchanged.

Syntax:

ClassName (const ClassName &obj) {

// Copy data members from obj to the new object

Q. What is Polymorphism? Discuss its type?


 The word “polymorphism” means having many forms. In simple words.
 we can define polymorphism as the ability of a message to be displayed in more than
one form.
 A real-life example of polymorphism is a person who at the same time can have
different characteristics. A man at the same time is a father, a husband, and an
employee. So the same person exhibits different behavior in different situations. This
is called polymorphism.
 Polymorphism is considered one of the important features of Object-Oriented
Programming.

Compile-Time Polymorphism

 This type of polymorphism is achieved by function overloading or operator


overloading.
 The overloaded functions are invoked by matching the type and number of
arguments.
 This information is available at the compile time and, therefore, compiler selects the
appropriate function at the compile time.
 It is achieved by function overloading and operator overloading which is also known
as static binding or early binding.
 Compile time polymorphism is also known as static polymorphism.
Function Overloading

 When multiple functions have the same name but different parameters, it is called
function overloading.

 Functions can be overloaded by changing the number of arguments or/and changing


the type of arguments
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. We know that the task of this operator is to add two
operands. So a single operator ‘+’, when placed between integer operands, adds
them and when placed between string operands, concatenates them.

Runtime Polymorphism
 This type of polymorphism is achieved by Function Overriding and virtual functions.
 Late binding and dynamic polymorphism are other names for runtime
polymorphism.
 The function call is resolved at runtime in runtime polymorphism.
 In contrast, with compile time polymorphism, the compiler determines which
function call to bind to the object after deducing it at runtime.
Function Overriding

Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
Virtual Function
A virtual function is a member function that is declared in the base class using the keyword
virtual and is re-defined (Overridden) in the derived class.

 They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
 A virtual function is called during Runtime

Q Difference between oops and structured programming.

Structured Programming Object-Oriented Programming

It relies on concept of objects that contain data


It is a subset of procedural programming.
and code.

Programs are divided into small programs or


Programs are divided into objects or entities.
functions.

It is all about facilitating creation of


It is all about creating objects that usually contain
programs with readable code and reusable
both functions and data.
components.

Its main aim is to improve and increase Its main aim is to improve and increase both
quality, clarity, and development time of quality and productivity of system analysis and
computer program. design.

It generally follows “Top-Down Approach”. It generally follows “Bottom-Up Approach”.

It provides less flexibility and abstraction as It provides more flexibility and abstraction as
compared to object-oriented programming. compared to structured programming.
It is more difficult to modify structured It is less difficult to modify object-oriented
program and reuse code as compared to programs and reuse code as compared to
object-oriented programs. structured programs.

It gives more importance of code. It gives more importance to data.

Q. What is Manipulators? Discuss 3 predefined manipulators?


 A manipulator in C++ is a function or object that modifies the input/output (I/O)
stream behavior.
 Manipulators are used with the cin and cout streams to format the output efficiently.
 Manipulators are found in the iostream and iomanip libraries.
 Manipulators are predefined functions that help in formatting output.
 The output data is manipulated on display according to the programmer's choice.
endl (End Line Manipulator)
 The endl manipulator inserts a newline (\n) and flushes the output buffer.
 It is commonly used to move to the next line while displaying output.

setw(n) (Set Width Manipulator)


 setw(n) sets the width of the next output.
 It ensures that the output takes at least n characters of space.
setprecision(n) (Set Decimal Precision)
 setprecision(n) sets the number of digits displayed after the decimal point.
 Works best with the fixed manipulator to display a fixed number of decimal places.

Note:

 fixedensures decimal places remain constant.


 Without fixed, setprecision(n) applies to total digits, not just after the decimal

Q. WAP to input a number and find its factorial by using default constructor in c++.
Q. What is Operator?
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical
computations on given values. They are the foundation of any programming language.

For example: int sum = 5 + 3; // '+' is an operator that adds two numbers.

Arithmetic Operators
Arithmetic operators are used to perform arithmetic or mathematical operations on the
operands. For example, ‘+’ is used for addition.
Relational Operators
Relational operators are used for the comparison of the values of two operands. For
example, ‘>’ check right operand is greater.
Logical Operators
Logical operators are used to combine two or more conditions or constraints or to
complement the evaluation of the original condition in consideration. The result returns a
Boolean value, i.e., true or false.
Bitwise Operators
Bitwise operators are works on bit-level. So, compiler first converted to bit-level and then
the calculation is performed on the operands.
Assignment Operators

Assignment operators are used to assign value to a variable. We assign the value of right
operand into left operand according to which assignment operator we use.
Ternary Operator
the ternary or conditional operator ( ? : ) is the shortest form of writing conditional
statements. It can be used as an inline conditional statement in place of if-else to execute
some conditional code.

Left Shift Operator (<<)


 The left shift(<<) is a binary operator that takes two numbers, left shifts the bits of
the first operand, and the second operand decides the number of places to shift.
 In other words, left-shifting an integer “a” with an integer “b” denoted as ‘(a<<b)’ is
equivalent to multiplying a with 2^b (2 raised to power b).
 Moves bits to the left by a specified number of positions.
 Equivalent to multiplying by 2^n (where n is the number of shifts).
 Syntax : result = number << shift_count;
Right Shift Operator (>>)
Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.
In other words, right-shifting an integer “a” with an integer “b” denoted as ‘(a>>b)‘ is
equivalent to dividing a with 2^b.
 Moves bits to the right by a specified number of positions.
 Equivalent to dividing by 2^n (where n is the number of shifts).
result = number >> shift_count;

Q. What is Inheritance? Explain its all types.


Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a
new class (called the child class or derived class) to acquire the properties and behaviors of
an existing class (called the parent class or base class).

 Inheritance is one of the core principles of Object-Oriented Programming (OOP)


 It allows a class (child class) to inherit properties and behaviors (methods) from
another class (parent class).
 It helps in code reusability, hierarchy representation, and method overriding.
 To inherit from a class, use the : symbol.
 Inheritance is widely used in real-world applications like software development,
game development, and artificial intelligence.
 It follows a "is-a" relationship, meaning if Car inherits from Vehicle, then a Car is a
type of Vehicle.
 This feature helps in organizing complex code structures efficiently while ensuring
flexibility and scalability in software development.
Syntax:

class derived_class_name : access-specifier base_class_name


{
// body ....
};

Single Inheritance

Single inheritance allows a child class to inherit from a single parent class. The child class can
access the properties and methods of the parent class, promoting code reusability.
one base class is inherited by one derived class only.

Multiple Inheritance
 Multiple inheritance allows a child class to inherit from two or more parent classes.
 This enables the child class to access features from multiple sources but can lead to
complexity.
 Multiple inheritance is a feature in C++ where a class can inherit from more than
one base class.
 This means a derived class can have properties and behaviors of multiple parent
classes.
 It helps in code reusability but can introduce ambiguity issues if two base classes
have the same function name.

 Scope resolution operator (::) is used to resolve ambiguity.


 Virtual inheritance is used to handle the diamond problem.

Multilevel Inheritance
 Multilevel inheritance involves a chain of inheritance where a child class inherits
from a parent class, which itself is derived from another class.
 This creates a hierarchical structure.
 There can be any number of levels.
 Multilevel Inheritance in C++ is the process of deriving a class from another derived
class.
 When one class inherits another class it is further inherited by another class. It is
known as multi-level inheritance.
 For example, if we take Grandfather as a base/parents class then Father is the
derived/child class that has features of Grandfather and then Child is the also derived
class that is derived from the sub-class Father which inherits all the features of
Father.
Hierarchical Inheritance

 Hierarchical inheritance allows multiple child classes to inherit from a single parent
class.
 Each child class gets access to the parent class’s features independently.
 In Hierarchical inheritance, more than one sub-class inherits the property of a single
base class.
 There is one base class and multiple derived classes.
 Several other classes inherit the derived classes as well.
 Hierarchical structures form a tree-like structure. It is similar to that, mango and
apple both are fruits; both inherit the property of fruit. Fruit will be the Base class,
and mango and apple are sub-classes.

Hybrid Inheritance

 Hybrid Inheritance is implemented by combining more than one type of inheritance.


 For example: Combining Hierarchical inheritance and Multiple Inheritance will create
hybrid inheritance in C++
 It is used when a class inherits from multiple classes following a mixed approach.
 There is no particular syntax of hybrid inheritance. We can just combine two of the
above inheritance types.

Q. What is operator overloading in c++ ? WAP to overload the + operator.

 C++ has the ability to provide the operators with a special meaning for a data type,
this ability is known as operator overloading.
 Operator overloading is a compile-time polymorphism.
 For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +.
 It is an idea of giving special meaning to an existing operator in C++ without changing
its original meaning.
 Operator overloading is a feature in C++ that allows customizing the behavior of
operators (+, -, *, /, etc.) for user-defined data types (such as classes and structures).

 Overloading does not change operator precedence.


 It improves code readability and usability.
 The operator keyword is used for overloading.
 Sizeof, Scope resolution (::), (.(dot),Ternary (?:)
Q. What is friend function? WAP to implement friend function?

 A friend function in C++ is a function that is not a member of a class but has access to
its private and protected members.
 A friend function is a non-member function or ordinary function of a class, which is
declared as a friend using the keyword “friend” inside the class. By declaring a
function as a friend, all the access permissions are given to the function.
 A friend function is not called using an object.
 It cannot access class members directly (must use an object reference).
 It helps in operator overloading and external function access.
 A friend class can access private and protected members of other classes in which it
is declared as a friend.
 Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++.
 They are not the member functions of the class but can access and manipulate the
private and protected members of that class for they are declared as friends.
 A friend function can be declared in any section of the class i.e. public or private or
protected.
A friend function can be: A global function, A member function of another class
Function overloading
 Function overloading is a feature of object-oriented programming where two or
more functions can have the same name but different parameters.
 When a function name is overloaded with different jobs it is called Function
Overloading.
 In Function Overloading “Function” name should be the same and the arguments
should be different.
 Function overloading can be considered as an example of
a polymorphism feature in C++.
 If multiple functions having same name but parameters of the functions should
be different is known as Function Overloading.
 If we have to perform only one operation and having same name of the functions
increases the readability of the program.
 Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the function such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
to understand the behavior of the function because its name differs.
 Function overloading allows you to define multiple functions with the same name
but different parameters.
Q. Write the difference between function overloading and overriding.

Function Overloading Function Overriding

The concept through which we can define The concept through which we define a
two or more functions with the same name function in parent class and the child class
and different numbers and parameters is with the same return type and parameters
known as function overloading. is known as function overriding.

An example of compile time polymorphism. An example of run time polymorphism.

Function signatures should be different. Function signatures should be the same.

Overloaded functions are in same scope. Overridden functions are in different scopes.

A function has the ability to load multiple A function can be overridden only a single
times. time.

In function overloading, we don’t need In function overriding, we need an


inheritance. inheritance concept.

No keyword is used during function When the function is defined, it is preceded


overloading. by 'virtual' keyword in main class.

Destructor can't be overloaded. Destructor can be overridden.


Q. What is Template? Discuss the advantage of template.
 A template is a simple yet very powerful tool in C++.
 The simple idea is to pass the data type as a parameter so that we don’t need to
write the same code for different data types.
 For example, a software company may need to sort() for different data types. Rather
than writing and maintaining multiple codes, we can write one sort() and pass the
datatype as a parameter.
 C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by the keyword ‘class’.
 A template in C++ is a powerful feature that allows writing generic code that works
with any data type. It enables code reusability by defining a single function or class
that can operate on different data types without rewriting the entire logic.

Syntax:

template <typename T>


T function_name(T parameter) {
// Function body
}

Advantages of Templates in C++


1. Code Reusability

o Templates eliminate the need to write separate functions or classes for


different data types.
o Example: A single function can handle both int and float types.
2. Type Safety

o Unlike macros, templates provide type checking at compile time, reducing


errors.
3. Flexibility
o Templates allow the creation of generic functions and classes that work with
multiple data types.
4. Better Maintainability

o Writing one function instead of multiple overloaded functions makes the


code easier to manage.
5. Efficiency
o No runtime overhead since templates are expanded at compile time, making
them faster than polymorphism in some cases.

You might also like