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