SlideShare una empresa de Scribd logo
1 de 34
Objects and Classes
Objectives
 To create objects using copy constructors with initial data
copied from another object of the same type
 To customize copy constructors to perform deep copy
 To understand the difference between instance and static
variables and functions
 To enable friend functions and friend classes to access a class’s
private members
 To create immutable objects from immutable classes
 Difference between struct and class
 To prevent multiple declarations using the #ifndef inclusion
guard directive
Copy Constructors
 Each class may define several overloaded constructors and one
destructor.
 Additionally, every class has a copy constructor. The signature
of the copy constructor is:
ClassName(ClassName &)
For example, the copy constructor for the Circle class is
Circle(Circle &)
 The copy constructor can be used to create an object initialized
with another object’s data. By default, the copy constructor
simply copies each data field in one object to its counterpart in
the other object.
Shallow Copy vs. Deep Copy
The default copy constructor or assignment operator for
copying objects performs a shallow copy, rather than a
deep copy.
In shallow copy, if a data field in a class is a pointer, the
address of the pointer is copied rather than its contents.
In deep copy, if a data field in a class is a pointer, the
contents of that objects are copied rather than its
reference.
Customizing Copy Constructor
 The default copy constructor or assignment
operator = performs a shallow copy.
 To perform a deep copy, you have to implement
the copy constructor.
Shallow Copy - Example
class Test
{
private:
int i;
int *p;
public:
Test(int x, int y)
{ i = x;
p = new int(y);
}
void setVal(int x, int y)
{ i = x; *p = y; }
void show()
{
cout<<"i = "<<i<<endl;
cout<<"p = "<<*p<<endl;
}
};
void main()
{
Test t1(5,10);
Test t2(t1);
t1.setVal(20,30);
t1.show();
t2.show();
}
Shallow Copy - Example
class Test{
private:
int i;
int *p;
public:
Test(int x, int y){
i = x;
p = new int(y);
}
Test(Test &t) {
i = t.i;
p = t.p;
}
void setVal(int x, int y)
{ i = x; *p = y; }
void show() {
cout<<"i = "<<i<<endl;
cout<<"p = "<<*p<<endl;
}
};
void main()
{
Test t1(1,12);
Test t2(t1);
t1.setVal(0,70);
t1.show();
t2.show();
}
Deep Copy - Example
class Test{
private:
int i;
int *p;
public:
Test(int x, int y){
i = x;
p = new int(y);
}
Test(Test &t) {
i = t.i;
p = new int(*t.p);
}
void setVal(int x, int y)
{ i = x; *p = y; }
void show() {
cout<<"i = "<<i<<endl;
cout<<"p = "<<*p<<endl;
}
};
void main()
{
Test t1(5,1);
Test t2(t1);
t1.setVal(90,3);
t1.show();
t2.show();
}
Deep Copy - Example
class Test {
private:
int i;
int *p;
public:
Test(int x, int y):i(x), p(new int(y))
{ }
Test(Test &t):i(t.i), p(new int(*t.p))
{ }
void setVal(int x, int y)
{
i = x;
*p = y;
}
void show()
{
cout<<"i = "<<i<<endl;
cout<<"p = "<<*p<<endl;
}
};
void main()
{
Test t1(5,10);
Test t2(t1);
t1.setVal(2,80);
t1.show();
t2.show();
}
Shallow Copy of Dynamic Array - Example
class Test
{ public:
int size;
int *arr;
Test(int size):size(size),arr(new int[size])
{ for(int i=0; i<3; i++)
arr[i] = 0;
}
Test(Test &t):size(t.size), arr(t.arr)
{
std::copy(t.arr, t.arr + size, arr);
}
void show()
{ for(int i=0; i<3; i++)
cout<<arr[i]<<" ";
}
};
void main()
{
Test t1(3);
Test t2(t1);
t1.arr[0] = 31;
t1.show();
t2.show();
}
Deep Copy of Dynamic Array - Example
class Test
{ public:
int size;
int *arr;
Test(int size):size(size),arr(new int[size])
{ for(int i=0; i<3; i++)
arr[i] = 0;
}
Test(Test &t):size(t.size), arr(new int[size])
{
std::copy(t.arr, t.arr + size, arr);
}
void show()
{ for(int i=0; i<3; i++)
cout<<arr[i]<<" ";
}
};
void main()
{
Test t1(3);
Test t2(t1);
t1.arr[0] = 31;
t1.show();
t2.show();
}
Deep Copy - Example
class Test{
private:
int i; int *p;
public:
Test(int x, int y){
i = x; p = new int(y);
}
Test(Test &t)
{ i = t.i;
p = new int(*t.p);
}
void setVal(int x, int y)
{ i = x; *p = y; }
void show() {
cout<<"i = "<<i<<endl;
cout<<"p = "<<*p<<endl;
}
~Test()
{ delete p;
cout<<“ pointer deleted”;
}
};
void main()
{
Test t1(5,1);
Test t2(t1);
t1.setVal(90,3);
t1.show();
t2.show();
}
Deep Copy of Dynamic Array - Example
class Test
{ public:
int size; int *arr;
Test(int size):size(size),arr(new int[size])
{ for(int i=0; i<3; i++)
arr[i] = 0;
}
Test(Test &t):size(t.size), arr(new int[size])
{
std::copy(t.arr, t.arr + size, arr);
}
void show()
{ for(int i=0; i<3; i++)
cout<<arr[i]<<" ";
}
~Test()
{ delete[] arr;
cout<<“array deleted”;
}
};
void main()
{
Test t1(3);
Test t2(t1);
t1.arr[0] = 31;
t1.show();
t2.show();
}
string, c_str, strtok
#include <iostream>
#include <cstring>
#include <string>
void main ()
{
std::string str (“Making tokens of this string");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
// cstr now contains a c-string copy of str
char * p = std::strtok (cstr," ");
while (p!=0)
{ std::cout << p << 'n';
p = strtok(NULL," ");
}
delete[] cstr;
}
Instance and Static Members
Circle
-radius: double
-numberOfObjects: int
+getNumberOfObjects(): int
+getArea(): double
1 radius
circle1
radius = 1
numberOfObjects = 2
instantiate
instantiate
Memory
2
5 radius
Number of Objects
UML Notation:
+: public variables or functions
-: private variables or functions
underline: static variables or functions
circle2
radius = 5
numberOfObjects = 2
Example – Non-Static data members
class Test{
private:
int count;
public:
Test()
{
count = 0;
}
void IncrementCounter()
{ count++; }
void show()
{ cout<<count<<endl; }
};
void main()
{
Test t1, t2, t3;
t1.IncrementCounter();
t2.IncrementCounter();
t3.IncrementCounter();
t1.show();
t2.show();
t3.show();
}
Example – Static data members
class Test{
private:
static int count;
public:
Test()
{
// count = 0;
}
void IncrementCounter()
{ count++; }
void show()
{ cout<<count<<endl; }
};
int Test::count = 0;
void main()
{
Test t1, t2, t3;
t1.IncrementCounter();
t2.IncrementCounter();
t3.IncrementCounter();
t1.show();
t2.show();
t3.show();
}
Example – Static data members
class Test{
private:
static int count;
public:
Test()
{
// count = 0;
}
void IncrementCounter()
{ count++; }
static void show()
{ cout<<count<<endl; }
};
int Test::count = 0;
void main()
{
Test t1, t2, t3;
t1.IncrementCounter();
t2.IncrementCounter();
t3.IncrementCounter();
Test::show();
Test::show();
Test::show();
}
Example – static data members
class Circle
{
private:
double radius;
static int numberOfObjects;
public:
Circle();
Circle(double);
double getArea();
double getRadius();
void setRadius(double);
static int getNumberOfObjects();
};
int Circle::numberOfObjects = 0;
Circle::Circle()
{
radius = 1;
numberOfObjects++;
}
Circle::Circle(double radius)
{
this->radius = radius;
numberOfObjects++;
}
double Circle::getArea()
{
return radius * radius * 3.14159;
}
double Circle::getRadius()
{
return radius;
}
void Circle::setRadius(double radius)
{
this->radius = (radius >= 0) ? radius : 0;
}
int Circle::getNumberOfObjects()
{
return numberOfObjects;
}
Example – static data members
int main()
{
cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl;
Circle circle1;
cout << "The area of the circle of radius “;<< circle1.getRadius() << " is " << circle1.getArea() << endl;
cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl;
Circle circle2(5.0);
cout << "The area of the circle of radius "<< circle2.getRadius() << " is " << circle2.getArea() << endl;
cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl;
circle1.setRadius(3.3);
cout << "The area of the circle of radius "<< circle1.getRadius() << " is " << circle1.getArea() << endl;
cout << "circle1.getNumberOfObjects() returns "<< circle1.getNumberOfObjects() << endl;
cout << "circle2.getNumberOfObjects() returns "<< circle2.getNumberOfObjects() << endl;
return 0;
}
Use Class Name
 Use ClassName::functionName(arguments) to invoke
a static function and ClassName::staticVariable.
This improves readability because the user can easily
recognize the static function and data in the class.
Instance or Static?
How do you decide whether a variable or function should be
instance or static?
A variable or function that is dependent on (or related to) a specific
instance of the class should be an instance variable or function.
A variable or function that is not dependent on (or not related to) a
specific instance of the class should be a static variable or function.
Example: Every circle has its own radius. Radius is dependent on a
specific circle. Therefore, radius is an instance variable of the Circle
class. Since the getArea function is dependent on a specific circle, it
is an instance function. Since numberOfObjects is not dependent on
any specific instance, it should be declared static.
Friend Functions and Classes
 Private members of a class cannot be accessed from
outside of the class.
 Occasionally, it is convenient to allow some trusted
functions and classes to access a class’s private members.
 C++ enables you to use the friend keyword to declare
friend functions and friend classes for a class so these
functions and classes can access the class’s private
members.
Friend Function – Example
class Beta;
class Alpha {
private:
int data1;
public:
Alpha() : data1(5) { }
friend int friFunc(Alpha, Beta);
};
class Beta {
private:
int data2;
public:
Beta() : data2(10) { }
friend int friFunc(Alpha, Beta);
};
int friFunc(Alpha a, Beta b)
{
return a.data1+b.data2;
}
void main() {
Alpha al;
Beta bt;
cout<<friFunc(al, bt);
}
Function firFunc is able to access
private data members of both
classes.
Friend Functions can be declared in
both public and private sections of
the class
Friend class – Example
class Alpha {
private:
int data;
public:
Alpha() : data(5) { }
friend class Beta;
};
class Beta {
public:
void func1(Alpha a)
{ cout<<a.data; }
void func2(Alpha a)
{ cout<<a.data; }
};
void main()
{
Alpha al;
Beta bt;
bt.func1(al);
bt.func2(al);
}
Friend class – Example
class X {
private:
int a, b;
public:
X( ): a(10), b(20)
{ }
friend class Y;
};
class Y {
public:
void showValues(X obj);
};
void Y::showValues(X obj)
{
cout<<obj.a;
cout<<obj.b;
}
void main()
{
X xObj;
Y yObj;
yObj.showValues(xObj);
}
showValues() of class Y is
able to access private data
members of class X.
Immutable Objects and Classes
 If the contents of an object cannot be changed once the
object is created, the object is called an immutable object
and its class is called an immutable class.
Person
-id: int
-birthDate: Date*
+Person(id: int, year: int,
month: int, day: int)
+getId(): int
+getBirthDate(): Date*
The id of this person.
The birth date of this person.
Constructs a Person with the specified id, year, month,
and day.
Returns the id of this person.
Returns the birth date of this person.
Immutable Objects and Classes
For a class to be immutable,
 It must mark all data fields private
 It must not provide any mutator functions and
 No accessor functions that would return a reference
or pointer to a mutable data fields
 Preventing changes in data members from a member
function by making member function constant: const
function
 By declaring object as const, you can’t modify it
const Member Functions
 A const member function guarantees that it will never
modify any of its class’s member data.
class Test
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{ alpha = 99; } //OK
void conFunc() const //const member function
{ alpha = 99; } //ERROR: can’t modify a member
};
const Member Function - Example
class Distance
{
private:
int feet;
public:
Distance():feet(0)
{ }
Distance(int ft): feet(ft)
{ }
Distance addDist(Distance d)
{
Distance temp(5);
temp.feet += d.feet;
return temp;
}
void showDistance() const
{
cout<<“Feet = “<<feet;
}
};
void main()
{
Distance dist1, dist3;
Distance dist2(11);
dist3 = dist1.addDist(dist2);
cout<<dist1.showDistance();
cout<<dist2.showDistance();
cout<<dist3.showDistance();
}
const Member Function – Example
class Alpha{
private:
int a;
float b;
public:
Alpha():a(0),b(0.0)
{ }
void func1( ) const
{
// a = 10; error: const function
cout<<a;
}
void func2( ) const
{ cout<<b; }
};
void main() {
Alpha al;
al.func1();
al.func2();
}
const Object
 When an object is declared as const, you can’t
modify it.
 It follows that you can use only const member
functions with it, because they’re the only ones
that guarantee not to modify it.
const Object - Example
class Distance
{
private:
int feet;
public:
Distance():feet(0)
{ }
Distance(int ft): feet(ft)
{ }
int getDistance()
{
cout<<“Enter Distance”;cin>>feet;
}
void showDistance() const
{ cout<<“Feet = “<<feet;
cout<<“Inches=“<<inches;
}
};
void main()
{
const Distance dist1;
//cout<<dist1.getDistance();
// Error: getDistance not constant
cout<<dist1.showDistance();
}
//getShow is ok because it is
constant function
Difference between class and struct
By default, all data fields of a struct are public. However,
by default, all data fields of a class are private.
The struct type defined in (a) can be replaced by the class
defined in (b) by using public access modifier.
struct Student
{
int id;
char firstName[30];
char mi;
char lastName[30];
};
(a)
class Student
{
public:
int id;
char firstName[30];
char mi;
char lastName[30];
};
(b)

Más contenido relacionado

La actualidad más candente

Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181Mahmoud Samir Fayed
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184Mahmoud Samir Fayed
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templateskinan keshkeh
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180Mahmoud Samir Fayed
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbookManusha Dilan
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31Mahmoud Samir Fayed
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 

La actualidad más candente (20)

Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202
 
Java practical
Java practicalJava practical
Java practical
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184The Ring programming language version 1.5.3 book - Part 31 of 184
The Ring programming language version 1.5.3 book - Part 31 of 184
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
 
Class method
Class methodClass method
Class method
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Templates
TemplatesTemplates
Templates
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
oop objects_classes
oop objects_classesoop objects_classes
oop objects_classes
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 

Similar a Oop objects_classes

麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202Mahmoud Samir Fayed
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.pptinstaface
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212Mahmoud Samir Fayed
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
The Ring programming language version 1.7 book - Part 37 of 196
The Ring programming language version 1.7 book - Part 37 of 196The Ring programming language version 1.7 book - Part 37 of 196
The Ring programming language version 1.7 book - Part 37 of 196Mahmoud Samir Fayed
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedPawanMM
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180Mahmoud Samir Fayed
 

Similar a Oop objects_classes (20)

麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202
 
New C# features
New C# featuresNew C# features
New C# features
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
class and objects
class and objectsclass and objects
class and objects
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
The STL
The STLThe STL
The STL
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212
 
C# Generics
C# GenericsC# Generics
C# Generics
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
The Ring programming language version 1.7 book - Part 37 of 196
The Ring programming language version 1.7 book - Part 37 of 196The Ring programming language version 1.7 book - Part 37 of 196
The Ring programming language version 1.7 book - Part 37 of 196
 
02.adt
02.adt02.adt
02.adt
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
Bc0037
Bc0037Bc0037
Bc0037
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Oops concept
Oops conceptOops concept
Oops concept
 
Op ps
Op psOp ps
Op ps
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180
 

Último

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Último (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

Oop objects_classes

  • 2. Objectives  To create objects using copy constructors with initial data copied from another object of the same type  To customize copy constructors to perform deep copy  To understand the difference between instance and static variables and functions  To enable friend functions and friend classes to access a class’s private members  To create immutable objects from immutable classes  Difference between struct and class  To prevent multiple declarations using the #ifndef inclusion guard directive
  • 3. Copy Constructors  Each class may define several overloaded constructors and one destructor.  Additionally, every class has a copy constructor. The signature of the copy constructor is: ClassName(ClassName &) For example, the copy constructor for the Circle class is Circle(Circle &)  The copy constructor can be used to create an object initialized with another object’s data. By default, the copy constructor simply copies each data field in one object to its counterpart in the other object.
  • 4. Shallow Copy vs. Deep Copy The default copy constructor or assignment operator for copying objects performs a shallow copy, rather than a deep copy. In shallow copy, if a data field in a class is a pointer, the address of the pointer is copied rather than its contents. In deep copy, if a data field in a class is a pointer, the contents of that objects are copied rather than its reference.
  • 5. Customizing Copy Constructor  The default copy constructor or assignment operator = performs a shallow copy.  To perform a deep copy, you have to implement the copy constructor.
  • 6. Shallow Copy - Example class Test { private: int i; int *p; public: Test(int x, int y) { i = x; p = new int(y); } void setVal(int x, int y) { i = x; *p = y; } void show() { cout<<"i = "<<i<<endl; cout<<"p = "<<*p<<endl; } }; void main() { Test t1(5,10); Test t2(t1); t1.setVal(20,30); t1.show(); t2.show(); }
  • 7. Shallow Copy - Example class Test{ private: int i; int *p; public: Test(int x, int y){ i = x; p = new int(y); } Test(Test &t) { i = t.i; p = t.p; } void setVal(int x, int y) { i = x; *p = y; } void show() { cout<<"i = "<<i<<endl; cout<<"p = "<<*p<<endl; } }; void main() { Test t1(1,12); Test t2(t1); t1.setVal(0,70); t1.show(); t2.show(); }
  • 8. Deep Copy - Example class Test{ private: int i; int *p; public: Test(int x, int y){ i = x; p = new int(y); } Test(Test &t) { i = t.i; p = new int(*t.p); } void setVal(int x, int y) { i = x; *p = y; } void show() { cout<<"i = "<<i<<endl; cout<<"p = "<<*p<<endl; } }; void main() { Test t1(5,1); Test t2(t1); t1.setVal(90,3); t1.show(); t2.show(); }
  • 9. Deep Copy - Example class Test { private: int i; int *p; public: Test(int x, int y):i(x), p(new int(y)) { } Test(Test &t):i(t.i), p(new int(*t.p)) { } void setVal(int x, int y) { i = x; *p = y; } void show() { cout<<"i = "<<i<<endl; cout<<"p = "<<*p<<endl; } }; void main() { Test t1(5,10); Test t2(t1); t1.setVal(2,80); t1.show(); t2.show(); }
  • 10. Shallow Copy of Dynamic Array - Example class Test { public: int size; int *arr; Test(int size):size(size),arr(new int[size]) { for(int i=0; i<3; i++) arr[i] = 0; } Test(Test &t):size(t.size), arr(t.arr) { std::copy(t.arr, t.arr + size, arr); } void show() { for(int i=0; i<3; i++) cout<<arr[i]<<" "; } }; void main() { Test t1(3); Test t2(t1); t1.arr[0] = 31; t1.show(); t2.show(); }
  • 11. Deep Copy of Dynamic Array - Example class Test { public: int size; int *arr; Test(int size):size(size),arr(new int[size]) { for(int i=0; i<3; i++) arr[i] = 0; } Test(Test &t):size(t.size), arr(new int[size]) { std::copy(t.arr, t.arr + size, arr); } void show() { for(int i=0; i<3; i++) cout<<arr[i]<<" "; } }; void main() { Test t1(3); Test t2(t1); t1.arr[0] = 31; t1.show(); t2.show(); }
  • 12. Deep Copy - Example class Test{ private: int i; int *p; public: Test(int x, int y){ i = x; p = new int(y); } Test(Test &t) { i = t.i; p = new int(*t.p); } void setVal(int x, int y) { i = x; *p = y; } void show() { cout<<"i = "<<i<<endl; cout<<"p = "<<*p<<endl; } ~Test() { delete p; cout<<“ pointer deleted”; } }; void main() { Test t1(5,1); Test t2(t1); t1.setVal(90,3); t1.show(); t2.show(); }
  • 13. Deep Copy of Dynamic Array - Example class Test { public: int size; int *arr; Test(int size):size(size),arr(new int[size]) { for(int i=0; i<3; i++) arr[i] = 0; } Test(Test &t):size(t.size), arr(new int[size]) { std::copy(t.arr, t.arr + size, arr); } void show() { for(int i=0; i<3; i++) cout<<arr[i]<<" "; } ~Test() { delete[] arr; cout<<“array deleted”; } }; void main() { Test t1(3); Test t2(t1); t1.arr[0] = 31; t1.show(); t2.show(); }
  • 14. string, c_str, strtok #include <iostream> #include <cstring> #include <string> void main () { std::string str (“Making tokens of this string"); char * cstr = new char [str.length()+1]; std::strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str char * p = std::strtok (cstr," "); while (p!=0) { std::cout << p << 'n'; p = strtok(NULL," "); } delete[] cstr; }
  • 15. Instance and Static Members Circle -radius: double -numberOfObjects: int +getNumberOfObjects(): int +getArea(): double 1 radius circle1 radius = 1 numberOfObjects = 2 instantiate instantiate Memory 2 5 radius Number of Objects UML Notation: +: public variables or functions -: private variables or functions underline: static variables or functions circle2 radius = 5 numberOfObjects = 2
  • 16. Example – Non-Static data members class Test{ private: int count; public: Test() { count = 0; } void IncrementCounter() { count++; } void show() { cout<<count<<endl; } }; void main() { Test t1, t2, t3; t1.IncrementCounter(); t2.IncrementCounter(); t3.IncrementCounter(); t1.show(); t2.show(); t3.show(); }
  • 17. Example – Static data members class Test{ private: static int count; public: Test() { // count = 0; } void IncrementCounter() { count++; } void show() { cout<<count<<endl; } }; int Test::count = 0; void main() { Test t1, t2, t3; t1.IncrementCounter(); t2.IncrementCounter(); t3.IncrementCounter(); t1.show(); t2.show(); t3.show(); }
  • 18. Example – Static data members class Test{ private: static int count; public: Test() { // count = 0; } void IncrementCounter() { count++; } static void show() { cout<<count<<endl; } }; int Test::count = 0; void main() { Test t1, t2, t3; t1.IncrementCounter(); t2.IncrementCounter(); t3.IncrementCounter(); Test::show(); Test::show(); Test::show(); }
  • 19. Example – static data members class Circle { private: double radius; static int numberOfObjects; public: Circle(); Circle(double); double getArea(); double getRadius(); void setRadius(double); static int getNumberOfObjects(); }; int Circle::numberOfObjects = 0; Circle::Circle() { radius = 1; numberOfObjects++; } Circle::Circle(double radius) { this->radius = radius; numberOfObjects++; } double Circle::getArea() { return radius * radius * 3.14159; } double Circle::getRadius() { return radius; } void Circle::setRadius(double radius) { this->radius = (radius >= 0) ? radius : 0; } int Circle::getNumberOfObjects() { return numberOfObjects; }
  • 20. Example – static data members int main() { cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl; Circle circle1; cout << "The area of the circle of radius “;<< circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl; Circle circle2(5.0); cout << "The area of the circle of radius "<< circle2.getRadius() << " is " << circle2.getArea() << endl; cout << "Number of circle objects created: "<< Circle::getNumberOfObjects() << endl; circle1.setRadius(3.3); cout << "The area of the circle of radius "<< circle1.getRadius() << " is " << circle1.getArea() << endl; cout << "circle1.getNumberOfObjects() returns "<< circle1.getNumberOfObjects() << endl; cout << "circle2.getNumberOfObjects() returns "<< circle2.getNumberOfObjects() << endl; return 0; }
  • 21. Use Class Name  Use ClassName::functionName(arguments) to invoke a static function and ClassName::staticVariable. This improves readability because the user can easily recognize the static function and data in the class.
  • 22. Instance or Static? How do you decide whether a variable or function should be instance or static? A variable or function that is dependent on (or related to) a specific instance of the class should be an instance variable or function. A variable or function that is not dependent on (or not related to) a specific instance of the class should be a static variable or function. Example: Every circle has its own radius. Radius is dependent on a specific circle. Therefore, radius is an instance variable of the Circle class. Since the getArea function is dependent on a specific circle, it is an instance function. Since numberOfObjects is not dependent on any specific instance, it should be declared static.
  • 23. Friend Functions and Classes  Private members of a class cannot be accessed from outside of the class.  Occasionally, it is convenient to allow some trusted functions and classes to access a class’s private members.  C++ enables you to use the friend keyword to declare friend functions and friend classes for a class so these functions and classes can access the class’s private members.
  • 24. Friend Function – Example class Beta; class Alpha { private: int data1; public: Alpha() : data1(5) { } friend int friFunc(Alpha, Beta); }; class Beta { private: int data2; public: Beta() : data2(10) { } friend int friFunc(Alpha, Beta); }; int friFunc(Alpha a, Beta b) { return a.data1+b.data2; } void main() { Alpha al; Beta bt; cout<<friFunc(al, bt); } Function firFunc is able to access private data members of both classes. Friend Functions can be declared in both public and private sections of the class
  • 25. Friend class – Example class Alpha { private: int data; public: Alpha() : data(5) { } friend class Beta; }; class Beta { public: void func1(Alpha a) { cout<<a.data; } void func2(Alpha a) { cout<<a.data; } }; void main() { Alpha al; Beta bt; bt.func1(al); bt.func2(al); }
  • 26. Friend class – Example class X { private: int a, b; public: X( ): a(10), b(20) { } friend class Y; }; class Y { public: void showValues(X obj); }; void Y::showValues(X obj) { cout<<obj.a; cout<<obj.b; } void main() { X xObj; Y yObj; yObj.showValues(xObj); } showValues() of class Y is able to access private data members of class X.
  • 27. Immutable Objects and Classes  If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. Person -id: int -birthDate: Date* +Person(id: int, year: int, month: int, day: int) +getId(): int +getBirthDate(): Date* The id of this person. The birth date of this person. Constructs a Person with the specified id, year, month, and day. Returns the id of this person. Returns the birth date of this person.
  • 28. Immutable Objects and Classes For a class to be immutable,  It must mark all data fields private  It must not provide any mutator functions and  No accessor functions that would return a reference or pointer to a mutable data fields  Preventing changes in data members from a member function by making member function constant: const function  By declaring object as const, you can’t modify it
  • 29. const Member Functions  A const member function guarantees that it will never modify any of its class’s member data. class Test { private: int alpha; public: void nonFunc() //non-const member function { alpha = 99; } //OK void conFunc() const //const member function { alpha = 99; } //ERROR: can’t modify a member };
  • 30. const Member Function - Example class Distance { private: int feet; public: Distance():feet(0) { } Distance(int ft): feet(ft) { } Distance addDist(Distance d) { Distance temp(5); temp.feet += d.feet; return temp; } void showDistance() const { cout<<“Feet = “<<feet; } }; void main() { Distance dist1, dist3; Distance dist2(11); dist3 = dist1.addDist(dist2); cout<<dist1.showDistance(); cout<<dist2.showDistance(); cout<<dist3.showDistance(); }
  • 31. const Member Function – Example class Alpha{ private: int a; float b; public: Alpha():a(0),b(0.0) { } void func1( ) const { // a = 10; error: const function cout<<a; } void func2( ) const { cout<<b; } }; void main() { Alpha al; al.func1(); al.func2(); }
  • 32. const Object  When an object is declared as const, you can’t modify it.  It follows that you can use only const member functions with it, because they’re the only ones that guarantee not to modify it.
  • 33. const Object - Example class Distance { private: int feet; public: Distance():feet(0) { } Distance(int ft): feet(ft) { } int getDistance() { cout<<“Enter Distance”;cin>>feet; } void showDistance() const { cout<<“Feet = “<<feet; cout<<“Inches=“<<inches; } }; void main() { const Distance dist1; //cout<<dist1.getDistance(); // Error: getDistance not constant cout<<dist1.showDistance(); } //getShow is ok because it is constant function
  • 34. Difference between class and struct By default, all data fields of a struct are public. However, by default, all data fields of a class are private. The struct type defined in (a) can be replaced by the class defined in (b) by using public access modifier. struct Student { int id; char firstName[30]; char mi; char lastName[30]; }; (a) class Student { public: int id; char firstName[30]; char mi; char lastName[30]; }; (b)