SlideShare a Scribd company logo
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

PDF
Object Oriented Programming using C++ - Part 3
PDF
Object Oriented Programming using C++ - Part 1
PDF
Object Oriented Programming using C++ - Part 4
PDF
Object Oriented Programming using C++ - Part 5
PPT
Bca 2nd sem u-2 classes & objects
PPT
C++ classes tutorials
PPTX
Oops presentation
PPTX
constructors and destructors in c++
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 5
Bca 2nd sem u-2 classes & objects
C++ classes tutorials
Oops presentation
constructors and destructors in c++

What's hot (18)

PPTX
PPTX
Compile time polymorphism
DOCX
Virtual function
PDF
Java ppt Gandhi Ravi (gandhiri@gmail.com)
PPT
Constructor and destructor in C++
PPTX
Functions in c++
PDF
Constructors destructors
PPT
Oops lecture 1
PDF
Functions in C++
PPT
Lec 42.43 - virtual.functions
PPTX
Polymorphism
PPTX
Oop objects_classes
PPT
C++: Constructor, Copy Constructor and Assignment operator
PPT
Constructor
PPTX
C# for C++ programmers
PDF
Introduction to objective c
PPTX
Qcon2011 functions rockpresentation_f_sharp
Compile time polymorphism
Virtual function
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Constructor and destructor in C++
Functions in c++
Constructors destructors
Oops lecture 1
Functions in C++
Lec 42.43 - virtual.functions
Polymorphism
Oop objects_classes
C++: Constructor, Copy Constructor and Assignment operator
Constructor
C# for C++ programmers
Introduction to objective c
Qcon2011 functions rockpresentation_f_sharp
Ad

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

PPT
Classes and objects
PPT
PDF
Class and object
PPTX
Lecture 2 (1)
PPTX
oopusingc.pptx
PPTX
OOP C++
PDF
PPTX
Classes and objects
PPTX
Introduction to Class a deep analysisadfas
PPSX
Arre tari mano bhosko ka pikina tari ma no piko
PDF
Lab 4 (1).pdf
PPTX
Classes and objects
PPT
4 Classes & Objects
PPTX
Lecture 4. mte 407
PPTX
lecture3.pptx
PPTX
Concept of Object-Oriented in C++
PDF
Chapter 7 C++ As OOP
PPTX
class c++
PPT
classes data type for Btech students.ppt
PPTX
C++ppt. Classs and object, class and object
Classes and objects
Class and object
Lecture 2 (1)
oopusingc.pptx
OOP C++
Classes and objects
Introduction to Class a deep analysisadfas
Arre tari mano bhosko ka pikina tari ma no piko
Lab 4 (1).pdf
Classes and objects
4 Classes & Objects
Lecture 4. mte 407
lecture3.pptx
Concept of Object-Oriented in C++
Chapter 7 C++ As OOP
class c++
classes data type for Btech students.ppt
C++ppt. Classs and object, class and object
Ad

Recently uploaded (20)

PPTX
Institutional Correction lecture only . . .
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Cell Types and Its function , kingdom of life
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
Institutional Correction lecture only . . .
Supply Chain Operations Speaking Notes -ICLT Program
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
TR - Agricultural Crops Production NC III.pdf
Pre independence Education in Inndia.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Cell Types and Its function , kingdom of life
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
Renaissance Architecture: A Journey from Faith to Humanism
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Final Presentation General Medicine 03-08-2024.pptx

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