SlideShare a Scribd company logo
1 of 61
Download to read offline
OOPS THROUGH C++
1
Dr. Chandra Sekhar Sanaboina
Assistant Professor
Department of Computer Science and Engineering
University College of Engineering Kakinada
Jawaharlal Nehru Technological University Kakinada
Website: https://drcs.info
Youtube Link:
https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
UNIT ā€“ II
CLASSES AND OBJECTS
&
CONSTRUCTORS AND DESTRUCTOR
2
AGENDA
ā€¢ Classes and Objects
ā€¢ Classes in C++
ā€¢ Declaring Objects
ā€¢ Access Specifiers and their Scope
ā€¢ Defining Member Function
ā€¢ Overloading Member Function
ā€¢ Nested class
ā€¢ Constructors and Destructors
ā€¢ Introduction
ā€¢ Characteristics of Constructor and Destructor
ā€¢ Application with Constructor
ā€¢ Constructor with Arguments (parameterized Constructors)
ā€¢ Destructors
3
CLASSES IN C++
4
CLASSES IN C++
ā€¢ C++ is an object-oriented programming language
ā€¢ Everything in C++ is associated with classes and objects
ā€¢ A class in C++ is the building block, that leads to Object-
Oriented programming
ā€¢ It is a user-defined data type
ā€¢ Holds its own Data Members and Member Functions
ā€¢ Data Members are the data variables
ā€¢ Member Functions are the functions used to manipulate these variables
ā€¢ Note: The Data Members and Member Functions defines the properties and
behavior of the objects in a Class.
ā€¢ Data members and Member Functions can be accessed and used
by creating an instance of that class
ā€¢ A C++ class is like a blueprint for an object
5
CLASSES IN C++ CONTDā€¦
ā€¢ Creating a Class
ā€¢ Syntax:
class <class_name>
{
Access Specifiers:
Data_Members;
Member_Functions();
};
ā€¢ Explanation to class creation in C++
ā€¢ class keyword is used to create a class
ā€¢ <class_name> specifies the name of the class
ā€¢ The body of class is defined inside the curly brackets
ā€¢ Inside the class we can declare the desired data members and member
functions with desired Access Specifiers
ā€¢ The class should always end with a semicolon (;) 6
CLASSES IN C++ CONTDā€¦
ā€¢ Example:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
float myFloat; // Attribute (float variable)
};
ā€¢ Explanation to class creation in C++
ā€¢ class keyword is used to create a class
ā€¢ MyClass specifies the name of the class
ā€¢ The public keyword is an Access Specifier
ā€¢ Inside the class we have declared two Data Members (Called as Attributes)
ā€¢ myNum of integer datatype
ā€¢ myFloat of Float datatype
ā€¢ The class should always end with a semicolon (;) 7
OBJECTS IN C++
8
OBJECTS IN C++
ā€¢ 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
ā€¢ To use the data and access functions defined in the class, we need to
create the objects
ā€¢ Declaring Objects:
ā€¢ Syntax:
ā€¢ Classname object_name
ā€¢ Example:
ā€¢ MyClass myObj;
ā€¢ MyClass is the class name
ā€¢ myObj is the name of the object
9
ACCESSING THE DATA
MEMBERS AND MEMBER
FUNCTIONS
10
ACCESSING DATA MEMBERS AND MEMBER
FUNCTIONS
ā€¢ The data members and member functions of
class can be accessed using the dot(ā€˜.ā€™)
operator with the object
ā€¢ For example if the name of object is myObj
ā€¢ We want to access the Data Member myNum then
we will have to write myObj.myNum
ā€¢ We want to access the member function
printName() then we will have to
write myObj.printName()
11
EXAMPLE PROGRAM
CREATING SINGLE OBJECT
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = ā€œChandu";
// Print attribute values
cout << myObj.myNum << "n";
cout << myObj.myString;
return 0;
}
12
EXAMPLE PROGRAM
CREATING MULTIPLE OBJECTS
// Create a Car class with some
attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
// Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
// Print attribute values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year << "n";
cout << carObj2.brand << " " <<
carObj2.model << " " << carObj2.year << "n";
return 0;
}
13
ACCESS SPECIFIERS
14
ACCESS SPECIFIERS AND THEIR SCOPE
ā€¢ Data hiding is one of the important features of Object Oriented
Programming which allows preventing the functions of a program
to access directly the internal data members of a class
ā€¢ The access restriction to the class members is specified by the
labeled
ā€¢ Public
ā€¢ Private, and
ā€¢ protected
ā€¢ These labels are called as Access Specifiers
ā€¢ Note 1: A class can have multiple public, protected, or private labeled
sections
ā€¢ Note 2: Each section remains in effect until either another section label
or the closing right brace of the class body is seen
ā€¢ Note 3: The default access for members and classes is private
15
ACCESS SPECIFIERS EXAMPLE
ā€¢ Example ā€“
Class Base
{
public:
//Public Members go here
private:
//Private Members go here
protected:
//Protected Members go here
};
16
PUBLIC ACCESS
SPECIFIER
17
PUBLIC ACCESS SPECIFIER
ā€¢ A public member is accessible from anywhere outside the class but
within a program
ā€¢ You can set and get the value of public variables without any member
function
18
PUBLIC ACCESS SPECIFIER EXAMPLE
#include <iostream>
using namespace std;
class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};
// Member functions definitions
double Line::getLength(void) {
return length ;
}
void Line::setLength( double len) {
length = len;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength()
<<endl;
// set line length without member function
line.length = 10.0; // OK: because length is
public
cout << "Length of line : " << line.length
<<endl;
return 0;
}
19
PRIVATE ACCESS
SPECIFIER
20
PRIVATE ACCESS SPECIFIER
ā€¢ A private member variable or function cannot be accessed, or even
viewed from outside the class
ā€¢ Only the class and friend functions can access private members
ā€¢ By default all the members of a class would be private
ā€¢ which means until you label a member, it will be assumed a private member
ā€¢ Practically, we define data in private section and related functions in
public section so that they can be called from outside of the class
21
PRIVATE ACCESS SPECIFIER EXAMPLE
class Box {
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
22
PRIVATE ACCESS SPECIFIER EXAMPLE
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
// Member functions definitions
double Box::getWidth(void) {
return width ;
}
void Box::setWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
Box box;
// set box length without member
function
box.length = 10.0; // OK: because
length is public
cout << "Length of box : " <<
box.length <<endl;
// set box width without member
function
// box.width = 10.0; // Error: because
width is private
box.setWidth(10.0); // Use member
function to set it.
cout << "Width of box : " <<
box.getWidth() <<endl;
return 0;
} 23
PROTECTED ACCESS
SPECIFIER
24
PROTECTED ACCESS SPECIFIER
ā€¢ A protected member variable or function is very
similar to a private member but it provided one
additional benefit that they can be accessed in child
classes which are called derived classes
25
PROTECTED ACCESS SPECIFIER EXAMPLE
#include <iostream>
using namespace std;
class Box {
protected:
double width;
};
class SmallBox:Box { // SmallBox is the
derived class.
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void) {
return width ;
}
void SmallBox::setSmallWidth( double wid
) {
width = wid;
}
// Main function for the program
int main() {
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<<
box.getSmallWidth() << endl;
return 0;
}
26
DEFINING MEMBER
FUNCTIONS
27
DEFINING MEMBER FUNCTION
ā€¢ A member function of a class is a function that has
its definition or its prototype within the class
definition like any other variable
ā€¢ It operates on any object of the class of which it is a
member, and has access to all the members of a
class for that object
ā€¢ There are 2 ways to define a member function:
ā€¢ Inside class definition
ā€¢ Outside class definition
28
DEFINING MEMBER FUNCTIONS INSIDE THE CLASS
DEFINITION
ā€¢ Defining a member function within the class definition declares the
function inline, even if you do not use the inline specifier
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};
29
DEFINING MEMBER FUNCTIONS OUTSIDE
THE CLASS DEFINITION
ā€¢ To define a member function outside the class definition we have to use the scope resolution
:: operator along with class name and function name
ā€¢ We have to use class name just before :: operator
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);
};
double Box :: getVolume(void)
{
return length * breadth * height;
}
ā€¢ A member function will be called using a dot operator (.) on a object where it will manipulate
data related to that object
Box myBox();
myBox.getVolume();
30
PROGRAMMING EXAMPLE
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
double Box::getVolume(void) {
return length * breadth * height;
}
void Box::setLength( double len ) {
length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
31
OVERLOADING MEMBER
FUNCTIONS
32
OVERLOADING MEMBER FUNCTION
ā€¢ We can have multiple definitions for the same function name in the
same scope
ā€¢ The definition of the function must differ from each other by the types
and/or the number of arguments in the argument list
ā€¢ We cannot overload function declarations that differ only by return
type
33
OVERLOADING MEMBER FUNCTIONS
EXAMPLE
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i <<
endl;
}
void print(double f) {
cout << "Printing float: " << f
<< endl;
}
void print(char* c) {
cout << "Printing character: "
<< c << endl;
}
};
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
34
NESTED CLASSES
35
NESTED CLASS
ā€¢ A nested class is a class that is declared in another class
ā€¢ The nested class is also a member variable of the
enclosing class and has the same access rights as the
other members
ā€¢ However, the member functions of the enclosing class
have no special access to the members of a nested class
36
NESTED CLASS EXAMPLE
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number
is "<<num;
}
};
};
int main() {
cout<<"Nested classes in
C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
37
CONSTRUCTORS
AND
DESTRUCTORS
38
CONSTRUCTORS AND DESTRUCTORS
ā€¢ Introduction
ā€¢ It is special member function of the class.
ā€¢ Constructors are special class members which are called by the
compiler every time an object of that class is instantiated
ā€¢ In C++, Constructor is automatically called when object (instance
of class) is created
ā€¢ Constructors have the same name as the class
ā€¢ Constructors may be defined inside or outside the class definition
ā€¢ There are 4 types of constructors:
ā€¢ Do Nothing Constructor
ā€¢ Default constructors
ā€¢ Parametrized constructors
ā€¢ Copy constructors
39
CONSTRUCTORS VS NORMAL MEMBER FUNCTIONS
ā€¢ A constructor is different from normal functions in
following ways:
ā€¢ Constructor has same name as the class itself
ā€¢ Constructors donā€™t have return type
ā€¢ A constructor is automatically called when an object is
created.
ā€¢ If we do not specify a constructor, C++ compiler
generates a default constructor for us (expects no
parameters and has an empty body).
40
DO NOTHING CONSTRUCTOR
ā€¢ Do nothing constructors are that type of constructor which
does not contain any statements
ā€¢ Do nothing constructor is the one which has no argument in
it and no return type.
41
DEFAULT CONSTRUCTORS
ā€¢ Default constructor is the constructor which
doesnā€™t take any argument
ā€¢ It has no parameters
ā€¢ Even if we do not define any constructor explicitly,
the compiler will automatically provide a default
constructor implicitly
42
DEFAULT CONSTRUCTORS EXAMPLE
using namespace std;
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
43
PARAMETERIZED CONSTRUCTORS
ā€¢ It is 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 44
PARAMETERIZED CONSTRUCTORS CONTDā€¦
ā€¢ When an object is declared in a parameterized constructor, the initial values have to be
passed as arguments to the constructor function
ā€¢ The normal way of object declaration may not work
ā€¢ The constructors can be called explicitly or implicitly
ā€¢ Explicit Call: Example e = Example(10, 20);
ā€¢ Implicit Call: Example e(10, 20);
ā€¢ Uses of Parameterized constructor:
ā€¢ It is used to initialize the various data elements of different objects with different
values when they are created
ā€¢ It is used to overload constructors
45
PARAMETERIZED CONSTRUCTORS EXAMPLE
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " <<
p1.getY();
return 0;
}
46
COPY CONSTRUCTORS
ā€¢ A copy constructor is a member function which initializes an
object using another object of the same class
ā€¢ Syntax:
ā€¢ ClassName (const ClassName &old_obj)
{
Body of the function
}
obj is a reference to an object that is being used to initialize another
object
ā€¢ Note:
ā€¢ Whenever we define one or more non-default constructors (with
parameters) for a class, a default constructor (without parameters)
should also be explicitly defined as the compiler will not provide a
default constructor in this case
ā€¢ However, it is not necessary but itā€™s considered to be the best
practice to always define a default constructor
47
COPY CONSTRUCTORS EXAMPLE
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1;
}
// Copy constructor
Point(const Point &p1) {x = p1.x; y =
p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor
is called here
Point p2 = p1; // Copy constructor is
called here
// Let us access values assigned by
constructors
cout << "p1.x = " << p1.getX() << ",
p1.y = " << p1.getY();
cout << "np2.x = " << p2.getX() << ",
p2.y = " << p2.getY();
return 0;
}
48
WHEN IS A USER-DEFINED COPY
CONSTRUCTOR NEEDED?
ā€¢ If we donā€™t define our own copy constructor, the C++ compiler
creates a default copy constructor for each class which does a
member-wise copy between objects
ā€¢ The compiler created copy constructor works fine in general
ā€¢ We need to define our own copy constructor only if an object has
pointers or any runtime allocation of the resource like filehandle, a
network connection..etc.
ā€¢ i.e., If the class has pointer variables and has some dynamic memory
allocations, then it is a must to have a copy constructor
49
SHALLOW COPY
The Default Copy Constructor does only Shallow Copy
50
SHALLOW COPY EXAMPLE
#include <iostream>
using namespace std;
class Demo
{
int a;
int b;
int *p;
public:
Demo()
{
p=new int;
}
void setdata(int x,int y,int z)
{
a=x;
b=y;
*p=z;
}
void showdata()
{
std::cout << "value of a is : " <<a<< std::en
dl;
std::cout << "value of b is : " <<b<< std::en
dl;
std::cout << "value of *p is : " <<*p<< std::
endl;
}
};
int main()
{
Demo d1;
d1.setdata(4,5,7);
Demo d2 = d1;
d2.showdata();
return 0;
} 51
DEEP COPY
ā€¢ Deep copy is possible only with user defined copy constructor
ā€¢ In user defined copy constructor, we make sure that pointers
(or references) of copied object point to new memory locations.
52
DEEP COPY EXAMPLE
#include <iostream>
using namespace std;
class Demo
{
public:
int a;
int b;
int *p;
Demo()
{
p=new int;
}
Demo(Demo &d)
{
a = d.a;
b = d.b;
p = new int;
*p = *(d.p);
}
void setdata(int x,int y,int z)
{
a=x;
b=y;
*p=z;
}
void showdata()
{
std::cout << "value of a is : " <<a<<
std::endl;
std::cout << "value of b is : " <<b<<
std::endl;
std::cout << "value of *p is : " <<*p
<< std::endl;
}
};
int main()
{
Demo d1;
d1.setdata(4,5,7);
Demo d2 = d1;
d2.showdata();
return 0;
}
53
COPY CONSTRUCTORS CONTDā€¦
ā€¢ Example:
myClass t1, t2;
myClass t3=t1;
t2=t1;
ā€¢ Copy constructor is called when a new object is created from
an existing object, as a copy of the existing object
ā€¢ Assignment operator is called when an already initialized
object is assigned a new value from another existing object.
54
COPY CONSTRUCTORS CONTDā€¦
ā€¢ Why argument to a copy constructor must be passed as a
reference?
ā€¢ Copy constructor itself is a function
ā€¢ So if we pass an argument by value in a copy constructor, a call to copy
constructor would be made to call copy constructor which becomes a non-
terminating chain of calls. Therefore compiler doesnā€™t allow parameters to
be passed by value.
55
COPY CONSTRUCTORS CONTDā€¦
ā€¢ Why copy constructor argument should be const in C++?
ā€¢ When we create our own copy constructor, we pass an object by
reference and we generally pass it as a const reference
ā€¢ One reason for passing const reference is, we should use const in C++
wherever possible so that objects are not accidentally modified
ā€¢ This is one good reason for passing reference as const
56
COPY CONSTRUCTORS CONTDā€¦
ā€¢ Can we make copy constructor private?
ā€¢ Yes, a copy constructor can be made private
ā€¢ When we make a copy constructor private in a class, objects of that class
become non-copyable
ā€¢ This is particularly useful when our class has pointers or dynamically
allocated resources
57
CHARACTERISTICS OF CONSTRUCTORS
ā€¢ Characteristics of Constructors
ā€¢ They should be declared in the public section
ā€¢ They do not have any return type, not even void
ā€¢ They get automatically invoked when the objects are created
ā€¢ They cannot be inherited ā€¦ though derived class can call the base
class constructor
ā€¢ Like other functions, they can have default arguments
ā€¢ You cannot refer to their address
ā€¢ Constructors cannot be virtual
58
DESTRUCTORS
ā€¢ Destructors
ā€¢ Destructor is another special member function that is called by the
compiler when the scope of the object ends
ā€¢ As the name implies, destructors are used to destroy the objects that
have been created by the constructor within the C++ program
ā€¢ Destructor names are same as the class name but they are preceded by
a tilde (~)
ā€¢ It is a good practice to declare the destructor after the end of using
constructor
ā€¢ The destructor neither takes an argument nor returns any value
ā€¢ The compiler implicitly invokes upon the exit from the program for
cleaning up storage that is no longer accessible
ā€¢ Here's the basic declaration procedure of a destructor:
ā€¢ ~classname() { }
59
CHARACTERISTICS OF DESTRUCTORS
ā€¢ Characteristics of Destructors
ā€¢ The destructor has the same name as that of the class prefixed by the tilde character ā€˜~ā€™
ā€¢ The destructor cannot have arguments
ā€¢ It has no return type
ā€¢ Destructors cannot be overloaded i.e., there can be only one destructor in a class
ā€¢ In the absence of user defined destructor, it is generated by the compiler
ā€¢ The destructor is executed automatically when the control reaches the end of class scope
to destroy the object
ā€¢ They cannot be inherited
60
THE END
61

More Related Content

What's hot

Virtual function
Virtual functionVirtual function
Virtual functionharman kaur
Ā 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
Ā 
Functions in c++
Functions in c++Functions in c++
Functions in c++HalaiHansaika
Ā 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructorsPranali Chaudhari
Ā 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1rehan16091997
Ā 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsPrincess Sam
Ā 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar Gaurav
Ā 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classessidra tauseef
Ā 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
Ā 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
Ā 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
Ā 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
Ā 

What's hot (18)

Kotlin
KotlinKotlin
Kotlin
Ā 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
Ā 
Virtual function
Virtual functionVirtual function
Virtual function
Ā 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Ā 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Ā 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
Ā 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Ā 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Ā 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
Ā 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Ā 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
Ā 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Ā 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
Ā 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Ā 
Constructor
ConstructorConstructor
Constructor
Ā 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Ā 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Ā 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
Ā 

Similar to Object Oriented Programming using C++ - Part 2

OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3SURBHI SAROHA
Ā 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectsecondakay
Ā 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
Ā 
Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Enam Khan
Ā 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
Ā 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2Aadil Ansari
Ā 
lecture3.pptx
lecture3.pptxlecture3.pptx
lecture3.pptxShahin4220
Ā 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
Ā 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
Ā 
Class and object
Class and objectClass and object
Class and objectprabhat kumar
Ā 

Similar to Object Oriented Programming using C++ - Part 2 (20)

OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
Ā 
OOP C++
OOP C++OOP C++
OOP C++
Ā 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
Ā 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
Ā 
C++ Notes
C++ NotesC++ Notes
C++ Notes
Ā 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Ā 
Class and object
Class and objectClass and object
Class and object
Ā 
OOP.ppt
OOP.pptOOP.ppt
OOP.ppt
Ā 
Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.
Ā 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
Ā 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
Ā 
C++.pptx
C++.pptxC++.pptx
C++.pptx
Ā 
lecture3.pptx
lecture3.pptxlecture3.pptx
lecture3.pptx
Ā 
ccc
cccccc
ccc
Ā 
class c++
class c++class c++
class c++
Ā 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
Ā 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Ā 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
Ā 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Ā 
Class and object
Class and objectClass and object
Class and object
Ā 

Recently uploaded

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
Ā 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
Ā 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
Ā 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
Ā 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A BeƱa
Ā 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
Ā 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
Ā 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
Ā 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
Ā 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
Ā 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
Ā 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
Ā 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
Ā 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
Ā 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
Ā 

Recently uploaded (20)

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
Ā 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Ā 
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Ā 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
Ā 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
Ā 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
Ā 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
Ā 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
Ā 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
Ā 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
Ā 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
Ā 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
Ā 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
Ā 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Ā 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
Ā 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
Ā 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Ā 

Object Oriented Programming using C++ - Part 2

  • 1. OOPS THROUGH C++ 1 Dr. Chandra Sekhar Sanaboina Assistant Professor Department of Computer Science and Engineering University College of Engineering Kakinada Jawaharlal Nehru Technological University Kakinada Website: https://drcs.info Youtube Link: https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
  • 2. UNIT ā€“ II CLASSES AND OBJECTS & CONSTRUCTORS AND DESTRUCTOR 2
  • 3. AGENDA ā€¢ Classes and Objects ā€¢ Classes in C++ ā€¢ Declaring Objects ā€¢ Access Specifiers and their Scope ā€¢ Defining Member Function ā€¢ Overloading Member Function ā€¢ Nested class ā€¢ Constructors and Destructors ā€¢ Introduction ā€¢ Characteristics of Constructor and Destructor ā€¢ Application with Constructor ā€¢ Constructor with Arguments (parameterized Constructors) ā€¢ Destructors 3
  • 5. CLASSES IN C++ ā€¢ C++ is an object-oriented programming language ā€¢ Everything in C++ is associated with classes and objects ā€¢ A class in C++ is the building block, that leads to Object- Oriented programming ā€¢ It is a user-defined data type ā€¢ Holds its own Data Members and Member Functions ā€¢ Data Members are the data variables ā€¢ Member Functions are the functions used to manipulate these variables ā€¢ Note: The Data Members and Member Functions defines the properties and behavior of the objects in a Class. ā€¢ Data members and Member Functions can be accessed and used by creating an instance of that class ā€¢ A C++ class is like a blueprint for an object 5
  • 6. CLASSES IN C++ CONTDā€¦ ā€¢ Creating a Class ā€¢ Syntax: class <class_name> { Access Specifiers: Data_Members; Member_Functions(); }; ā€¢ Explanation to class creation in C++ ā€¢ class keyword is used to create a class ā€¢ <class_name> specifies the name of the class ā€¢ The body of class is defined inside the curly brackets ā€¢ Inside the class we can declare the desired data members and member functions with desired Access Specifiers ā€¢ The class should always end with a semicolon (;) 6
  • 7. CLASSES IN C++ CONTDā€¦ ā€¢ Example: class MyClass { // The class public: // Access specifier int myNum; // Attribute (int variable) float myFloat; // Attribute (float variable) }; ā€¢ Explanation to class creation in C++ ā€¢ class keyword is used to create a class ā€¢ MyClass specifies the name of the class ā€¢ The public keyword is an Access Specifier ā€¢ Inside the class we have declared two Data Members (Called as Attributes) ā€¢ myNum of integer datatype ā€¢ myFloat of Float datatype ā€¢ The class should always end with a semicolon (;) 7
  • 9. OBJECTS IN C++ ā€¢ 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 ā€¢ To use the data and access functions defined in the class, we need to create the objects ā€¢ Declaring Objects: ā€¢ Syntax: ā€¢ Classname object_name ā€¢ Example: ā€¢ MyClass myObj; ā€¢ MyClass is the class name ā€¢ myObj is the name of the object 9
  • 10. ACCESSING THE DATA MEMBERS AND MEMBER FUNCTIONS 10
  • 11. ACCESSING DATA MEMBERS AND MEMBER FUNCTIONS ā€¢ The data members and member functions of class can be accessed using the dot(ā€˜.ā€™) operator with the object ā€¢ For example if the name of object is myObj ā€¢ We want to access the Data Member myNum then we will have to write myObj.myNum ā€¢ We want to access the member function printName() then we will have to write myObj.printName() 11
  • 12. EXAMPLE PROGRAM CREATING SINGLE OBJECT class MyClass { // The class public: // Access specifier int myNum; // Attribute (int variable) string myString; // Attribute (string variable) }; int main() { MyClass myObj; // Create an object of MyClass // Access attributes and set values myObj.myNum = 15; myObj.myString = ā€œChandu"; // Print attribute values cout << myObj.myNum << "n"; cout << myObj.myString; return 0; } 12
  • 13. EXAMPLE PROGRAM CREATING MULTIPLE OBJECTS // Create a Car class with some attributes class Car { public: string brand; string model; int year; }; int main() { // Create an object of Car Car carObj1; carObj1.brand = "BMW"; carObj1.model = "X5"; carObj1.year = 1999; // Create another object of Car Car carObj2; carObj2.brand = "Ford"; carObj2.model = "Mustang"; carObj2.year = 1969; // Print attribute values cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "n"; cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "n"; return 0; } 13
  • 15. ACCESS SPECIFIERS AND THEIR SCOPE ā€¢ Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal data members of a class ā€¢ The access restriction to the class members is specified by the labeled ā€¢ Public ā€¢ Private, and ā€¢ protected ā€¢ These labels are called as Access Specifiers ā€¢ Note 1: A class can have multiple public, protected, or private labeled sections ā€¢ Note 2: Each section remains in effect until either another section label or the closing right brace of the class body is seen ā€¢ Note 3: The default access for members and classes is private 15
  • 16. ACCESS SPECIFIERS EXAMPLE ā€¢ Example ā€“ Class Base { public: //Public Members go here private: //Private Members go here protected: //Protected Members go here }; 16
  • 18. PUBLIC ACCESS SPECIFIER ā€¢ A public member is accessible from anywhere outside the class but within a program ā€¢ You can set and get the value of public variables without any member function 18
  • 19. PUBLIC ACCESS SPECIFIER EXAMPLE #include <iostream> using namespace std; class Line { public: double length; void setLength( double len ); double getLength( void ); }; // Member functions definitions double Line::getLength(void) { return length ; } void Line::setLength( double len) { length = len; } // Main function for the program int main() { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; // set line length without member function line.length = 10.0; // OK: because length is public cout << "Length of line : " << line.length <<endl; return 0; } 19
  • 21. PRIVATE ACCESS SPECIFIER ā€¢ A private member variable or function cannot be accessed, or even viewed from outside the class ā€¢ Only the class and friend functions can access private members ā€¢ By default all the members of a class would be private ā€¢ which means until you label a member, it will be assumed a private member ā€¢ Practically, we define data in private section and related functions in public section so that they can be called from outside of the class 21
  • 22. PRIVATE ACCESS SPECIFIER EXAMPLE class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); }; 22
  • 23. PRIVATE ACCESS SPECIFIER EXAMPLE #include <iostream> using namespace std; class Box { public: double length; void setWidth( double wid ); double getWidth( void ); private: double width; }; // Member functions definitions double Box::getWidth(void) { return width ; } void Box::setWidth( double wid ) { width = wid; } // Main function for the program int main() { Box box; // set box length without member function box.length = 10.0; // OK: because length is public cout << "Length of box : " << box.length <<endl; // set box width without member function // box.width = 10.0; // Error: because width is private box.setWidth(10.0); // Use member function to set it. cout << "Width of box : " << box.getWidth() <<endl; return 0; } 23
  • 25. PROTECTED ACCESS SPECIFIER ā€¢ A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes 25
  • 26. PROTECTED ACCESS SPECIFIER EXAMPLE #include <iostream> using namespace std; class Box { protected: double width; }; class SmallBox:Box { // SmallBox is the derived class. public: void setSmallWidth( double wid ); double getSmallWidth( void ); }; // Member functions of child class double SmallBox::getSmallWidth(void) { return width ; } void SmallBox::setSmallWidth( double wid ) { width = wid; } // Main function for the program int main() { SmallBox box; // set box width using member function box.setSmallWidth(5.0); cout << "Width of box : "<< box.getSmallWidth() << endl; return 0; } 26
  • 28. DEFINING MEMBER FUNCTION ā€¢ A member function of a class is a function that has its definition or its prototype within the class definition like any other variable ā€¢ It operates on any object of the class of which it is a member, and has access to all the members of a class for that object ā€¢ There are 2 ways to define a member function: ā€¢ Inside class definition ā€¢ Outside class definition 28
  • 29. DEFINING MEMBER FUNCTIONS INSIDE THE CLASS DEFINITION ā€¢ Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void) { return length * breadth * height; } }; 29
  • 30. DEFINING MEMBER FUNCTIONS OUTSIDE THE CLASS DEFINITION ā€¢ To define a member function outside the class definition we have to use the scope resolution :: operator along with class name and function name ā€¢ We have to use class name just before :: operator class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void); }; double Box :: getVolume(void) { return length * breadth * height; } ā€¢ A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object Box myBox(); myBox.getVolume(); 30
  • 31. PROGRAMMING EXAMPLE #include <iostream> using namespace std; class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box // Member functions declaration double getVolume(void); void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); }; // Member functions definitions double Box::getVolume(void) { return length * breadth * height; } void Box::setLength( double len ) { length = len; } void Box::setBreadth( double bre ) { breadth = bre; } void Box::setHeight( double hei ) { height = hei; } // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; return 0; } 31
  • 33. OVERLOADING MEMBER FUNCTION ā€¢ We can have multiple definitions for the same function name in the same scope ā€¢ The definition of the function must differ from each other by the types and/or the number of arguments in the argument list ā€¢ We cannot overload function declarations that differ only by return type 33
  • 34. OVERLOADING MEMBER FUNCTIONS EXAMPLE #include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print("Hello C++"); return 0; } 34
  • 36. NESTED CLASS ā€¢ A nested class is a class that is declared in another class ā€¢ The nested class is also a member variable of the enclosing class and has the same access rights as the other members ā€¢ However, the member functions of the enclosing class have no special access to the members of a nested class 36
  • 37. NESTED CLASS EXAMPLE #include<iostream> using namespace std; class A { public: class B { private: int num; public: void getdata(int n) { num = n; } void putdata() { cout<<"The number is "<<num; } }; }; int main() { cout<<"Nested classes in C++"<< endl; A :: B obj; obj.getdata(9); obj.putdata(); return 0; } 37
  • 39. CONSTRUCTORS AND DESTRUCTORS ā€¢ Introduction ā€¢ It is special member function of the class. ā€¢ Constructors are special class members which are called by the compiler every time an object of that class is instantiated ā€¢ In C++, Constructor is automatically called when object (instance of class) is created ā€¢ Constructors have the same name as the class ā€¢ Constructors may be defined inside or outside the class definition ā€¢ There are 4 types of constructors: ā€¢ Do Nothing Constructor ā€¢ Default constructors ā€¢ Parametrized constructors ā€¢ Copy constructors 39
  • 40. CONSTRUCTORS VS NORMAL MEMBER FUNCTIONS ā€¢ A constructor is different from normal functions in following ways: ā€¢ Constructor has same name as the class itself ā€¢ Constructors donā€™t have return type ā€¢ A constructor is automatically called when an object is created. ā€¢ If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body). 40
  • 41. DO NOTHING CONSTRUCTOR ā€¢ Do nothing constructors are that type of constructor which does not contain any statements ā€¢ Do nothing constructor is the one which has no argument in it and no return type. 41
  • 42. DEFAULT CONSTRUCTORS ā€¢ Default constructor is the constructor which doesnā€™t take any argument ā€¢ It has no parameters ā€¢ Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly 42
  • 43. DEFAULT CONSTRUCTORS EXAMPLE using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; } 43
  • 44. PARAMETERIZED CONSTRUCTORS ā€¢ It is 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 44
  • 45. PARAMETERIZED CONSTRUCTORS CONTDā€¦ ā€¢ When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function ā€¢ The normal way of object declaration may not work ā€¢ The constructors can be called explicitly or implicitly ā€¢ Explicit Call: Example e = Example(10, 20); ā€¢ Implicit Call: Example e(10, 20); ā€¢ Uses of Parameterized constructor: ā€¢ It is used to initialize the various data elements of different objects with different values when they are created ā€¢ It is used to overload constructors 45
  • 46. PARAMETERIZED CONSTRUCTORS EXAMPLE #include <iostream> using namespace std; class Point { private: int x, y; public: // Parameterized Constructor Point(int x1, int y1) { x = x1; y = y1; } int getX() { return x; } int getY() { return y; } }; int main() { // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; } 46
  • 47. COPY CONSTRUCTORS ā€¢ A copy constructor is a member function which initializes an object using another object of the same class ā€¢ Syntax: ā€¢ ClassName (const ClassName &old_obj) { Body of the function } obj is a reference to an object that is being used to initialize another object ā€¢ Note: ā€¢ Whenever we define one or more non-default constructors (with parameters) for a class, a default constructor (without parameters) should also be explicitly defined as the compiler will not provide a default constructor in this case ā€¢ However, it is not necessary but itā€™s considered to be the best practice to always define a default constructor 47
  • 48. COPY CONSTRUCTORS EXAMPLE #include<iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; } // Copy constructor Point(const Point &p1) {x = p1.x; y = p1.y; } int getX() { return x; } int getY() { return y; } }; int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; } 48
  • 49. WHEN IS A USER-DEFINED COPY CONSTRUCTOR NEEDED? ā€¢ If we donā€™t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects ā€¢ The compiler created copy constructor works fine in general ā€¢ We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like filehandle, a network connection..etc. ā€¢ i.e., If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor 49
  • 50. SHALLOW COPY The Default Copy Constructor does only Shallow Copy 50
  • 51. SHALLOW COPY EXAMPLE #include <iostream> using namespace std; class Demo { int a; int b; int *p; public: Demo() { p=new int; } void setdata(int x,int y,int z) { a=x; b=y; *p=z; } void showdata() { std::cout << "value of a is : " <<a<< std::en dl; std::cout << "value of b is : " <<b<< std::en dl; std::cout << "value of *p is : " <<*p<< std:: endl; } }; int main() { Demo d1; d1.setdata(4,5,7); Demo d2 = d1; d2.showdata(); return 0; } 51
  • 52. DEEP COPY ā€¢ Deep copy is possible only with user defined copy constructor ā€¢ In user defined copy constructor, we make sure that pointers (or references) of copied object point to new memory locations. 52
  • 53. DEEP COPY EXAMPLE #include <iostream> using namespace std; class Demo { public: int a; int b; int *p; Demo() { p=new int; } Demo(Demo &d) { a = d.a; b = d.b; p = new int; *p = *(d.p); } void setdata(int x,int y,int z) { a=x; b=y; *p=z; } void showdata() { std::cout << "value of a is : " <<a<< std::endl; std::cout << "value of b is : " <<b<< std::endl; std::cout << "value of *p is : " <<*p << std::endl; } }; int main() { Demo d1; d1.setdata(4,5,7); Demo d2 = d1; d2.showdata(); return 0; } 53
  • 54. COPY CONSTRUCTORS CONTDā€¦ ā€¢ Example: myClass t1, t2; myClass t3=t1; t2=t1; ā€¢ Copy constructor is called when a new object is created from an existing object, as a copy of the existing object ā€¢ Assignment operator is called when an already initialized object is assigned a new value from another existing object. 54
  • 55. COPY CONSTRUCTORS CONTDā€¦ ā€¢ Why argument to a copy constructor must be passed as a reference? ā€¢ Copy constructor itself is a function ā€¢ So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non- terminating chain of calls. Therefore compiler doesnā€™t allow parameters to be passed by value. 55
  • 56. COPY CONSTRUCTORS CONTDā€¦ ā€¢ Why copy constructor argument should be const in C++? ā€¢ When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference ā€¢ One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified ā€¢ This is one good reason for passing reference as const 56
  • 57. COPY CONSTRUCTORS CONTDā€¦ ā€¢ Can we make copy constructor private? ā€¢ Yes, a copy constructor can be made private ā€¢ When we make a copy constructor private in a class, objects of that class become non-copyable ā€¢ This is particularly useful when our class has pointers or dynamically allocated resources 57
  • 58. CHARACTERISTICS OF CONSTRUCTORS ā€¢ Characteristics of Constructors ā€¢ They should be declared in the public section ā€¢ They do not have any return type, not even void ā€¢ They get automatically invoked when the objects are created ā€¢ They cannot be inherited ā€¦ though derived class can call the base class constructor ā€¢ Like other functions, they can have default arguments ā€¢ You cannot refer to their address ā€¢ Constructors cannot be virtual 58
  • 59. DESTRUCTORS ā€¢ Destructors ā€¢ Destructor is another special member function that is called by the compiler when the scope of the object ends ā€¢ As the name implies, destructors are used to destroy the objects that have been created by the constructor within the C++ program ā€¢ Destructor names are same as the class name but they are preceded by a tilde (~) ā€¢ It is a good practice to declare the destructor after the end of using constructor ā€¢ The destructor neither takes an argument nor returns any value ā€¢ The compiler implicitly invokes upon the exit from the program for cleaning up storage that is no longer accessible ā€¢ Here's the basic declaration procedure of a destructor: ā€¢ ~classname() { } 59
  • 60. CHARACTERISTICS OF DESTRUCTORS ā€¢ Characteristics of Destructors ā€¢ The destructor has the same name as that of the class prefixed by the tilde character ā€˜~ā€™ ā€¢ The destructor cannot have arguments ā€¢ It has no return type ā€¢ Destructors cannot be overloaded i.e., there can be only one destructor in a class ā€¢ In the absence of user defined destructor, it is generated by the compiler ā€¢ The destructor is executed automatically when the control reaches the end of class scope to destroy the object ā€¢ They cannot be inherited 60