Lecture 2
Introduction to OOP
Khola Naseem
[email protected]
Credit: Khola Naseem
Access specifier or Access modifier:
➢ The access modifiers of C++ are
➢ Public
➢ Private
➢ Protected
➢ Data hiding is one of the key features of object-oriented programming languages
such as C++.
➢ Data hiding refers to restricting access to data members of a class. This makes it
impossible for other functions and classes to manipulate class data.
➢ However, it is also important to make some member functions and member data
accessible so that the hidden data can be manipulated indirectly.
➢ The access modifiers of C++ allows us to determine which class members are
accessible to other classes and functions, and which are not.
Credit: Khola Naseem
Constructor
➢ A constructor is a special type of member function that is called automatically
when an object is created.
➢ A class constructor provides the opportunity to initialize the new object as it is
created and to ensure that member variables contain valid values.
➢ It is a special kind of function in a class that differs in a few significant respects
from an ordinary member function.
➢ A class constructor always has the same name as the class.
➢ A constructor also does not return a value and therefore has no return
type. It is an error to specify a return type for a constructor.
➢ Example:
Credit: Khola Naseem
Constructor
➢ C++ Default Constructor:
➢ A constructor with no parameters is known as a default constructor. In the
example, Box() is a default constructor.
➢ Example: Output:
Credit: Khola Naseem
Constructor
➢ A constructor is a special type of member function that is called automatically
when an object is created.
➢ Example: Output:
Credit: Khola Naseem
Constructor
➢ C++ Default Default Constructor:
➢ if you don’t define a constructor for a class, the compiler supplies a default
default constructor. And no, the two “defaults” is no typo.
➢ A default default constructor has no parameters and its sole purpose is to allow
an object to be created.
➢ Credit: Khola Naseem
Constructor
➢ C++ Parameterized Constructor
➢ In C++, a constructor with parameters is known as a parameterized constructor.
➢ Output:
Credit: Khola Naseem
➢ C++ Parameterized Constructor
➢ In C++, a constructor with parameters is known as a parameterized constructor.
Output:
Credit: Khola Naseem
➢ C++ Constructor Overloading
➢ Overloaded constructors have the same name (name of the class) but the
different number of arguments. Depending upon the number and type of
arguments passed, the corresponding constructor is called.
Output:
Credit: Khola Naseem
destructor
➢ A destructor works opposite to constructor; it destructs the objects of classes. It
can be defined only once in a class. Like constructors, it is invoked
automatically.
➢ A destructor is defined like constructor. It must have same name as class. But it
is prefixed with a tilde sign (~).
➢ Destructors free up the memory used by the objects the constructor generated.
Credit: Khola Naseem