Object Oriented Programming (1) (2)
Object Oriented Programming (1) (2)
Syllabus
• Unit - I Object-Oriented Programming Concepts: Introduction, comparison between procedural
programming paradigm and object-oriented programming paradigm, basic concepts of object oriented
programming — concepts of an object and a class, interface and implementation of a class, operations on
objects, relationship among objects, abstraction, encapsulation, data hiding, inheritance, overloading,
polymorphism, messaging. Classes and Objects: Specifying a class, creating class objects, accessing
class members, access specifiers, static members, use of const keyword, friends of a class, empty classes,
nested classes, local classes, abstract classes, container classes, bit fields and classes.
• Unit – II
• Inheritance: Introduction, defining derived classes, forms of inheritance, ambiguity in multiple and
multipath inheritance, virtual base class, object slicing, overriding member functions, object composition
and delegation, order of execution of constructors and destructors. Pointers and Dynamic Memory
Management: Declaring and initializing pointers, accessing data through pointers, pointer arithmetic,
memory allocation (static and dynamic), dynamic memory management using new and delete operators,
pointer to an object, this pointer, pointer related problems - dangling/wild pointers, null pointer
assignment, memory leak and allocation failures.
• Unit - III Constructors and Destructors: Need for constructors and destructors,
copy constructor, dynamic constructors, explicit constructors, destructors,
constructors and destructors with static members, initializer lists. Operator
Overloading and Type Conversion: Overloading operators, rules for overloading
operators, overloading of various operators, type conversion - basic type to class
type, class type to basic type, class type to another class type. Virtual functions &
Polymorphism: Concept of binding - early binding and late binding, virtual
functions, pure virtual functions, abstract clasess, virtual destructors
return 0;
}
• #include
This is a preprocessor directive. The #include directive tells the compiler to include
the content of a file in the source code. For example, #include<iostream> tells the
compiler to include the standard iostream file which contains declarations of all the
standard input/output library functions.
• int main() { }
A function is a group of statements that are designed to perform a specific task. The
main() function is the entry point of every C++ program, no matter where the function
is located in the program.
The opening braces ‘{‘ indicates the beginning of the main function and the closing
braces ‘}’ indicates the ending of the main function.
• cout<<“Hello World”;
std::cout is an instance of the std::ostream class, that is used to display
output on the screen. Everything followed by the character << in double
quotes ” ” is displayed on the output device. The semi-colon character
at the end of the statement is used to indicate that the statement is
ending there.
• return 0
This statement is used to return a value from a function and indicates the
finishing of a function. This statement is basically used in functions to
return the results of the operations performed by a function.
C++ Classes and Objects
• A class is a user-defined data type, which holds its own data members
and member functions, which can be accessed and used by creating an
instance of that class. A C++ class is like a blueprint for an object.
• A Class is a user-defined data type that has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables together, these data
members and member functions define the properties and behaviour of
the objects in a Class.
• Note: When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Defining Class in C++
• A class is defined in C++ using the keyword class followed by the
name of the class. The following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};
Here, the access specifier defines the level of access to the class’s data
members.
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};
• Object in C++?
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, you need to create objects.
• Syntax to Create an Object
We can create an object of the given class in the same way we declare the
variables of any other inbuilt data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is created.
• Accessing Data Members and Member Functions
The data members and member functions of the class can be accessed using
the dot(‘.’) operator with the object. For example, if the name of the object
is obj and you want to access the member function with the
name printName() then you will have to write:
obj.printName()
• Syntax to Create an Object
We can create an object of the given class in the same way we declare the
variables of any other inbuilt data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is created.
• Accessing Data Members and Member Functions
The data members and member functions of the class can be accessed using the
dot(‘.’) operator with the object. For example, if the name of the object
is obj and you want to access the member function with the
name printName() then you will have to write:
obj.printName()
Example of Class and Object in C++
#include <iostream>
#include <string>
using namespace std;
// Define a class named 'Person'
class Person {
public:
// Data members
string name;
int age;
// Member function to introduce the person
void introduce() {
cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;
}
};
int main()
{
// Create an object of the Person class
Person person1; // accessing data members
person1.name = "Alice";
person1.age = 30; /
/ Call the introduce member method
person1.introduce();
return 0;
}
Output:
Hi, my name is Alice and I am 30 years old.
Access Modifiers
• In C++ classes, we can control the access to the members of the class using
Access Specifiers. Also known as access modifier, they are the keywords
that are specified in the class and all the members of the class under that
access specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
• Public: Members declared as public can be accessed from outside the class.
• Private: Members declared as private can only be accessed within the class
itself.
• Protected: Members declared as protected can be accessed within the class
and by derived classes.
• If we do not specify the access specifier, the private specifier is applied to
every member by default.
Interface and implementation of a class
• Interfaces are nothing but a way to describe the behavior of a class without
committing to the implementation of the class. In order to create an interface, we
need to create an abstract class which is having only pure virtual methods. In C++,
Interfaces are also called pure abstract classes.
• Pure Virtual Functions
A Pure Virtual Function is a function where we only declare the function but not
the function definition. The implementation for pure virtual methods is done at the
derived class by method/function overriding. A function is said to be a pure virtual
function if it is defined in the class as follows:
virtual datatype functionName(parameter1, parameter2,…) = 0
• Abstract Class
An abstract class is a class that is specially designed to be used as a base class. Abstract class must
have at least one pure virtual function. It may have variables and normal functions. The derived
classes of an abstract class must implement all the pure virtual functions of their base class or else
they too become abstract.
• Importance of Interfaces
Any class derived from the pure abstract class (Interface) must implement all of the methods of the
base class i.e. Interface.
Interface pointers can be passed to functions and classes thereby we can call the functions of the
derived class from there itself.
2. Aggregation: The aggregation is also a part-whole relationship but here in aggregation, the parts can
belong to more than one object at a time, and the whole object is not responsible for the existence of the
parts. To qualify as aggregation, a whole object and its part must have the following relationships:
• The part (member) is part of the object (class).
• The part (member) can belong to more than one object (class) at a time.
• The part (member) does not have its existence managed by the object (class).
• The part (member) does not know about the existence of the object (class).
Object Delegation
Object Delegation means using the object of another class as a class
member of another class. It is known as object delegation. Delegation can
be an alternative to inheritance, but in an inheritance, there is an i-s a
relationship, but in the delegation, there is no inheritance relationship
between the classes.
Types of Abstraction:
• Data abstraction – This type only shows the required information about the data
and ignores unnecessary details.
• Control Abstraction – This type only shows the required information about the
implementation and ignores unnecessary details.
Encapsulation
Encapsulation in C++ is defined as the wrapping up of data and information
in a single unit. In Object Oriented Programming, Encapsulation is defined
as binding together the data and the functions that manipulate them.
Two Important property of Encapsulation
• Data Protection: Encapsulation protects the internal state of an object by
keeping its data members private. Access to and modification of these data
members is restricted to the class’s public methods, ensuring controlled and
secure data manipulation.
• Information Hiding: Encapsulation hides the internal implementation
details of a class from external code. Only the public interface of the class is
accessible, providing abstraction and simplifying the usage of the class
while allowing the internal implementation to be modified without
impacting external code.
Features of Encapsulation
where,
class: keyword to create a new class
derived_class_name: name of the new class, which will inherit the base class
access-specifier: Specifies the access mode which can be either of private, public or
protected. If neither is specified, private is taken as default.
base-class-name: name of the base class.
• Example Type of inheritance
• // Base class
class Vehicle {
public: • Single Inheritance
string brand = "Ford";
void honk() {
• Multiple Inheritance
cout << "Tuut, tuut! \n" ; • Multilevel Inheritance
}
};
• Hierarchical Inheritance
• Hybrid Inheritance
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
}; Access Control and Inheritance
A derived class can access all the non-
int main() { private members of its base class. Thus
Car myCar;
myCar.honk();
base-class members that should not be
cout << myCar.brand + " " + myCar.model; accessible to the member functions of
return 0; derived classes should be declared private
} in the base class.
• When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance.
• We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied −
• Public Inheritance − When deriving a class from a public base class, public members
of the base class become public members of the derived class and protected members of
the base class become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the base class.
• Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class become protected members of the
derived class.
• Private Inheritance − When deriving from a private base
class, public and protected members of the base class become private members of the
derived class.
When to use Inheritance in C++
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and changing the
type of arguments. In simple terms, it is a feature of object-oriented programming
providing many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name.
B. 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.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. 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.
A. 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.
B. 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.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
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
Static Data Members
• Static data members are class members that are declared using static keywords. A static
member has certain special characteristics which are as follows:
• Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts
outside the class itself.
• It is visible can be controlled with the class access specifiers.
• Its lifetime is the entire program.
Syntax
className {
static data_type data_member_name;
.....
}
Static Data Member
As told earlier, the static members are only declared in the class declaration. If we
try to access the static data member without an explicit definition, the compiler
will give an error.
To access the static data member of any class we have to define it first and static
data members are defined outside the class definition. The only exception to this
are static const data members of integral type which can be initialized in the class
declaration.
Syntax
datatype class_name::var_name = value...;
For example, in the above program, we have initialized the static data member
using the following statement:
int A::x = 10
Note: The static data members are initialized at compile time so the definition of
static members should be present before the compilation of the program
Accessing a Static Member
We can access the static data member without creating the instance of the class. Just remember that we need to
initialize it beforehand. There are 2 ways of accessing static data members:
1. Accessing static data member using Class Name and Scope Resolution Operator
The class name and the scope resolution operator can be used to access the static data member even when there
are no instances/objects of the class present in the scope.
Syntax
Class_Name :: var_name
Example
A::x