SlideShare a Scribd company logo
1 of 69
Download to read offline
C++ 
L08-CLASSES, P1 
Programming Language 
Mohammad Shaker 
mohammadshaker.com 
@ZGTRShaker 
2010, 11, 12, 13, 14
OOP
Object Oriented Programming
Float, double, long double 
C++ data types 
Structured 
Simple 
Address 
Pointer 
Reference 
enum 
Floating 
Array 
Struct 
Union 
Class 
Char, Short, int, long, bool 
Integral
aclass
aClass 
•class 
–Concept 
•Information hiding 
•Prevent access to their inner workings 
•Encapsulation (private, public) 
–code 
•class 
–Is an extension of the idea of “struct” 
•class 
–User defined (programmer defined) type 
•Once class is defined it can be used as a type 
•Object of that class can be defined 
•No memory is allocated (like struct)
a Class 
•Class package data declarations with function declarations 
–Thus, coupling data with behavior 
•Used to implement “ADT” 
•Examples: 
–Time, Complex numbers,
Class 
•Type: 
–Time 
•Domain: 
–Any time value is a time in: Hour, minute, second 
•Operations: 
–Set the time 
–Print the time 
–Incrementing / decrementing time 
–Compare times 
•=, <, >
Class 
•Members 
–They are the components of the class 
•Attributes 
•Behaviors methods 
•Class instance 
–Object
Class 
•OOP and classes 
–Encapsulation 
–Composition 
–Inheritance 
–Reusable
Class 
#include<iostream> 
usingnamespacestd; 
classMyClass 
{ 
}; 
voidmain() 
{ 
} 
Compile & run 
#include<iostream> 
usingnamespacestd; 
classMyClass 
{ 
} 
voidmain() 
{ 
} 
Compiler error. Missing ; 
#include<iostream> 
usingnamespacestd; 
classMyClass 
{ 
inti; 
}; 
voidmain() 
{ 
} 
Compile and run 
#include<iostream> 
usingnamespacestd; 
classMyClass 
{ 
inti = 0; 
}; 
voidmain() 
{ 
} 
Compiler error 
Rule: 
You can’t initialize a variable when you declare it in classes.
Class 
•Function in classes 
–It can directly access any member of the class (WITHOUT PASSING IT AS PARAMETER) 
•Data members 
•Function members
Class 
•private: 
–Default access mode 
–Accessible just to the functions of the class and friends 
•public: 
–Accessible wherever object of class in scope 
•protected: 
–Accessible from members of their same class and friends class and also from their derived class
Class 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time()// constructor 
{ 
minute = second = hour = 0; 
} 
voidChangeTime(int,int,int) 
{ 
hour = 12; 
second = 0; 
minute = 0; 
} 
private: 
inthour; 
intminute; 
intsecond; 
}; 
voidmain() 
{} 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time();// constructor 
voidChangeTime(int,int,int); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
voidmain() 
{ 
}
Class 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{ 
minute = second = hour = 0; 
} 
voidTime::ChangeTime(int,int,int) 
{ 
hour = 12; 
second = 0; 
minute = 0; 
} 
voidmain() 
{} 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time::Time(); 
voidTime::ChangeTime(int,int,int); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{ 
minute = second = hour = 0; 
} 
voidTime::ChangeTime(int,int,int) 
{ 
hour = 12; 
second = 0; 
minute = 0; 
} 
voidmain() 
{}
Class 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":" 
<< second << endl; 
} 
voidmain() 
{Time T; 
T.PrintTime(); 
T.ChangeTime(11,1,5); 
T.PrintTime(); 
} 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":" 
<< second << endl; 
} 
voidmain() 
{Time T; 
T.hour = 12; 
T.PrintTime();T.ChangeTime(11,1,5); T.PrintTime(); 
} 
0:0:0 
11:5:1 
Compiler error 
Attempting to access private data members
Class 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
Time::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidmain() 
{Time T; 
T.PrintTime(); 
T.ChangeTime(11,1,5); 
T.PrintTime();} 
Compiler error 
Missing return type of the PrintTime() function
Class 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
voidChangeHourFromOutside(int); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidTime::ChangeHourFromOutside(intx) 
{hour = x;} 
voidmain() 
{ 
intTempHour = 0;Time T; 
cout << "Enter The Hour: "<< endl; 
cin >> TempHour;//5 
T.PrintTime(); 
T.ChangeHourFromOutside(TempHour); 
T.PrintTime(); 
T.ChangeTime(11,1,5); 
T.PrintTime(); 
} 
Enter The Hour: 
5 
0:0:0 
5:0:0 
11:5:1 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
voidChangeHourFromOutside(int); 
voidClear (); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidTime::ChangeHourFromOutside(intx) 
{hour = x;} 
voidTime::Clear () 
{minute = second = hour = 0; } 
voidmain() 
{ 
intTempHour = 0;Time T; 
cout << "Enter The Hour: "<< endl; 
cin >> TempHour;//5 
T.PrintTime(); T.ChangeHourFromOutside(TempHour); 
T.Clear(); 
T.PrintTime(); 
T.ChangeTime(11,1,5); 
T.PrintTime(); 
} 
Enter The Hour: 
5 
0:0:0 
0:0:0 
11:5:1
Class 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
voidChangeHourFromOutside(int); 
voidClear (); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidTime::ChangeHourFromOutside(intx) 
{hour = x;} 
voidTime::Clear () 
{minute = second = hour = 0; } 
voidmain() 
{ 
Time T1;Time *T2 = &T1; Time* &T3 = T2; 
T1.ChangeHourFromOutside(5); 
T1.PrintTime(); 
T2->PrintTime(); 
T3->PrintTime(); 
} 
5:0:0 
5:0:0 
5:0:0 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
voidChangeHourFromOutside(int); 
voidClear (); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidTime::ChangeHourFromOutside(intx) 
{hour = x;} 
voidTime::Clear () 
{minute = second = hour = 0; } 
voidmain() 
{ 
Time T1;Time *T2 = &T1; Time &T3 = *T2; 
T1.ChangeHourFromOutside(5); 
T1.PrintTime(); 
T2->PrintTime(); 
T3.PrintTime(); 
} 
5:0:0 
5:0:0 
5:0:0
Class 
classTime 
{ 
public: 
Time(); 
voidChangeTime(int,int,int); 
voidPrintTime(); 
voidChangeHourFromOutside(int); 
voidClear (); 
private: 
inthour = 9; 
intminute; 
intsecond; 
}; 
Time::Time()// constructor 
{minute = second = hour = 0; } 
voidTime::ChangeTime(intx1,intx2,intx3) 
{hour = x1; second = x2; minute = x3;} 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl;} 
voidTime::ChangeHourFromOutside(intx) 
{hour = x;} 
voidTime::Clear () 
{minute = second = hour = 0; } 
voidmain() 
{ 
Time T1;Time *T2 = &T1; Time &T3 = *T2; 
T1.ChangeHourFromOutside(5); 
T1.PrintTime(); 
T2->PrintTime(); 
T3.PrintTime(); 
} 
Compiler error, can’t initialize when declaring no matter what private or public
Class 
•A Getter, Get function: 
–Reads private data 
–“Query” functions 
•A Setter, Set function: 
–Modify private data 
–Perform a validity check before modifying private data 
–Notify if invalid values
Class 
classTime 
{public: 
Time(); 
voidSetTime(int,int,int);// set functions 
voidSetHour(int); 
voidSetMinute(int); 
voidSetSecond(int); 
intGetHour();// get functions 
intGetMinute() 
;intGetSecond(); 
voidPrintTime(); 
private: inthour;intminute;intsecond; }; 
Time::Time() 
{hour = minute = second = 0; }; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() {returnhour;}; 
intTime::GetMinute() {returnminute;}; 
intTime::GetSecond() {returnsecond;}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidmain() 
{ 
Time T; 
T.PrintTime(); 
T.SetHour(17); 
T.SetMinute(45); 
T.SetSecond(22); 
T.PrintTime(); 
T.SetHour(77); 
T.SetMinute(565); 
T.SetSecond(-1); 
T.PrintTime(); 
} 
0:0:0 
17:45:22 
0:0:0 
Press any key to continue
Class 
•Utility functions (Helper functions) 
–private 
•Support operations of public member functions 
•Not intended for direct client use 
–Examples
Organizing Your Classes
Organizing Your Classes 
•Implementing classes 
•Separating Interface from implementation 
•Headers (in header file) –if needed- 
–# ifndef Time_H 
–# define Time_H 
–// your code goes here 
–# endif
Organizing Your Classes 
In MyMain.cpp 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T; 
T.PrintTime(); 
T.SetHour(17); 
T.SetMinute(45); 
T.SetSecond(22); 
T.PrintTime(); 
T.SetHour(77); 
T.SetMinute(565); 
T.SetSecond(-1); 
T.PrintTime(); 
} 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
voidSetTime(int,int,int); 
voidSetHour(int); 
voidSetMinute(int); 
voidSetSecond(int); 
intGetHour(); 
intGetMinute(); 
intGetSecond(); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
In TimeClass.h 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time() 
{hour = minute = second = 0; }; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() {returnhour;}; 
intTime::GetMinute() {returnminute;}; 
intTime::GetSecond() {returnsecond;}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
In TimeClass.cpp
Live Demo
Class Constructor
Class 
•Constructor 
–What’s it for? 
•Used to guarantee the initialization of data members of class 
–The same name as class 
–Called implicitly when object is created 
•Whether calling it is statically or dynamically 
•(new operator) * 
–NO return type 
–Can be overloaded 
–Must be declared in public section 
________________________________________ 
* That means that we don’t need to call the constructor explicitly
Class 
•Constructor 
–Two types: 
•Without parameters (Default constructor) 
•With parameters 
–When creating a class object, C++ provides its own constructor for the object 
•Compiler implicitly creates default constructor 
•The programmer should explicitly define it, why? 
–Coz the data otherwise wouldn’t be guaranteed to be in consistent state 
–And that doesn’t perform any initialization of fundamentals variables
Class Constructor 
classTime 
{ 
public: 
voidSetTime(int,int,int); 
voidSetHour(int);voidSetMinute(int); 
voidSetSecond(int); 
intGetHour();intGetMinute(); 
intGetSecond(); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond); 
}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() {returnhour;}; 
intTime::GetMinute() {returnminute;}; 
intTime::GetSecond() {returnsecond;}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T; 
T.PrintTime(); 
T.SetHour(17); 
T.SetMinute(45); 
T.SetSecond(22); 
T.PrintTime(); 
T.SetHour(77); 
T.SetMinute(565); 
T.SetSecond(-1); 
T.PrintTime(); 
} 
2486832:1588607792:2486968 
17:45:22 
0:0:0 
Press any key to continue 
Cauze we didn’t write the constructor ourself so that the variables of the class hasn’t been initialized properly
Class Constructor 
classTime 
{public: 
Time(); 
voidSetTime(int,int,int);// set functions 
voidSetHour(int); 
voidSetMinute(int); 
voidSetSecond(int); 
intGetHour();// get functions 
intGetMinute() 
;intGetSecond(); 
voidPrintTime(); 
private: inthour;intminute;intsecond; }; 
Time::Time() 
{hour = minute = second = 0; }; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() {returnhour;}; 
intTime::GetMinute() {returnminute;}; 
intTime::GetSecond() {returnsecond;}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidmain() 
{ 
Time T; 
T.PrintTime(); 
T.SetHour(17); 
T.SetMinute(45); 
T.SetSecond(22); 
T.PrintTime(); 
T.SetHour(77); 
T.SetMinute(565); 
T.SetSecond(-1); 
T.PrintTime(); 
} 
0:0:0 
17:45:22 
0:0:0 
Press any key to continue
Overloading Constructors
Overloading Constructors 
•Constructors can be overloaded 
–must all have the same name as class 
•Overloading function in General allows you to use the same name for separate functions that have different argument lists
Overloading Constructors 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time(); 
Time(intTimeHour); 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time() 
{hour = minute = second = 0; }; 
Time::Time(intTimeHour) 
{hour = TimeHour; } 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T1; 
T1.PrintTime(); 
Time T2(2); 
T2.PrintTime(); 
} 
0:0:0 
2:1588607792:3011112 
Press any key to continue
Class –Member initializing list 
•Two ways to initialize member data by constructor 
–Code inserted in the constructor 
–A member initialization list 
•Given in the constructor definition 
–Not the prototype! 
•Follows the arguments list 
•Tells which member data to initialize with which arguments 
•So, how is the code? 
–Consists of 
»A colon followed by a comma separated list of member name argument pairs
Overloading Constructors 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time::Time():hour(),minute(),second(){}; 
Time(intTimeHour):hour(TimeHour),minute(0),second(0){};; 
Time(intTimeHour, intTimeMinute):hour(TimeHour),minute(TimeMinute),second(0){}; 
Time(intTimeHour, intTimeMinute, intTimeSecond):hour(TimeHour),minute(TimeMinute),second(TimeSecond){}; 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T1; 
T1.PrintTime(); 
Time T2(2); 
T2.PrintTime(); 
Time T3(2,3,06); 
T3.PrintTime(); 
} 
0:0:0 
2:0:0 
2:3:6
Overloading Constructors 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time::Time():hour(),minute(),second(); 
Time(intTimeHour):hour(TimeHour),minute(0),second(0){}; 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
Compiler error, missing {}
Overloading Constructors 
#include<iostream> 
usingnamespacestd; 
classTime 
{ 
public: 
Time::Time():hour(),minute(),second(){}; 
Time(intTimeHour):hour(TimeHour),minute(0),second(0){}; 
voidPrintTime(); 
private: 
inthour; 
intminute; 
intsecond; 
}; 
voidTime::PrintTime() 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T1; 
T1.PrintTime(); 
Time T2(2); 
T2.PrintTime(); 
Time T3(2,3,06); 
T3.PrintTime(); 
} 
Compiler error, no oveloaded function which takes 3 arguments
Classes Destructors
Classes Destructors 
•Same name as class 
•Preceded by tilde (~) 
•No arguments 
•No return value 
•Can’t be overloaded 
–Once only 
•When is it called? 
–When the object is destroyed 
•Termination housekeeping 
•new delete 
•If no explicit destructor was declared, 
–Compiler creates “Empty destructor”
Constructors VS Destructors 
•Orders of constructor destructor calls 
–Depends on scope 
–Generally, destructor are called in reverse order of constructor call
Constructors VS Destructors 
•Global scope object: 
–Constructors: 
•Before any other function (including main!) 
–Destructors: 
•When 
–main terminates 
–exit function is called 
•Not called with abort
Constructors VS Destructors 
•Automatic local object: 
–Constructors: 
•When object is defined 
–Each time entering scope 
–Destructors: 
•When 
–Objects leave scope 
•Not called with abort or exit
Constructors VS Destructors 
•static local object: 
–Constructors: 
•Exactly once 
•When the execution reaches point where the object is defined 
–Destructors: 
•When 
–main terminates 
–exit function is called 
•Not called with abort
Class Constructor 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: 
object(intId, char*MsgPtr); 
~object(); 
private: 
intobjectId; 
char*message; 
}; 
object::object(intId, char*MsgPtr) 
{ 
objectId = Id; 
message = MsgPtr; 
cout << objectId << " constructor runs for "<< message << endl; 
} 
object::~object() 
{ 
cout << objectId << " destructor runs for "<< message << endl; 
} 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
object first(1,"Global before main before CreateCrazy"); 
voidCreateCrazy(); 
voidmain() 
{ 
staticobject fourth(4, "static in main"); 
CreateCrazy(); 
} 
voidCreateCrazy() 
{ 
object fifth(5, "In CreateCrazy"); 
} 
1 constructor runs for Global before main before CreateCrazy 
4 constructor runs for static in main 
5 constructor runs for In CreateCrazy 
5 destructor runs for In CreateCrazy 
4 destructor runs for static in main 
1 destructor runs for Global before main before CreateCrazy 
Press any key to continue
Copy Constructors
Copy Constructor 
•Special member functions 
–That’s implicitly called in the following 3 situations 
•Object used to initialize another object 
–obj1(obj2) 
•Passing an object arguments by value to another object 
•Returning a temporary object as the return value of a function
Copy Constructor 
•C++ provides its own implicitly copy constructor 
–Overloaded constructor 
–Has no return value 
–Take only arguments as a reference to an object of the same class 
–The compiler provides a copy whose signature is: 
–Class_Name::Class_Name (const Class_Name&) 
–When an object is passed to a function, a simple bitwise (exact) copy of that object is made and given to the function
Copy Constructor 
•Assignment “=” 
–Assign object to object 
–Is done by 
•Each member in the first object is copied individually to the same member in the second one 
•Done to the object that are value arguments
Copy Constructor 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: object(); 
object(constobject& ob); 
~object(); 
voiddisplay(); 
private: intnum, den;}; 
object::object() 
{cout << "constructing"<< endl; num = 0; den = 1;} 
object::object(constobject& ob) 
{cout << "copy constructing"<< endl; num = ob.num; den = ob.den;} 
object::~object() 
{cout << "destructing"<< endl;} 
voidobject::display() 
{cout << "num = "<< num << ", den = "<< den << endl;} 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidPlay(object x) 
{ 
cout << "In function Play"<< endl; 
x.display(); 
} 
voidmain() 
{ 
object ob1; object ob2; 
cout << "In main, before Play"<< endl; 
ob1.display(); 
ob2.display(); 
Play (ob1); 
cout << "In main, after calling Play "<< endl; 
ob1.display(); 
ob2.display(); 
ob2 = ob1; 
cout << "In main, after assignemet "<< endl; 
ob1.display(); 
ob2.display(); 
}
Copy Constructor 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: object(); 
object(constobject& ob); 
~object(); 
voiddisplay(); 
private: intnum, den;}; 
object::object() 
{cout << "constructing"<< endl; num = 0; den = 1;} 
object::object(constobject& ob) 
{cout << "copy constructing"<< endl; num = ob.num; den = ob.den;} 
object::~object() 
{cout << "destructing"<< endl;} 
voidobject::display() 
{cout << "num = "<< num << ", den = "<< den << endl;} 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidPlay(object x) 
{ 
cout << "In function Play"<< endl; 
x.display(); 
} 
voidmain() 
{ 
object ob1; object ob2; 
cout << "In main, before Play"<< endl; 
ob1.display(); 
ob2.display(); 
Play (ob1); 
cout << "In main, after calling Play "<< endl; 
ob1.display(); 
ob2.display(); 
ob2 = ob1; 
cout << "In main, after assignemet "<< endl; 
ob1.display(); 
ob2.display(); 
} 
constructing 
constructing 
In main, before Play 
num = 0, den = 1 
num = 0, den = 1 
copy constructing 
In function Play 
num = 0, den = 1 
destructing 
In main, after calling Play 
num = 0, den = 1 
num = 0, den = 1 
In main, after assignemet 
num = 0, den = 1 
num = 0, den = 1 
destructing 
destructing 
Press any key to continue
Cloning Objects
Shallow copy VS Deep Copy 
•C++,by default, use shallow copy for initializations and assignments 
•With shallow copy, if the object contains a pointer to allocated memory 
–The copy will also point to the memory as does the original object 
–Deleting the original object may cause the copied object to incorrectly disappear!
Shallow copy VS Deep Copy 
•If the class data points to a dynamic data 
–You should write your own copy constructor to create a “deep copy” of the dynamic data 
–A deep copy copies not only the class data members, but also makes a separate stored copy of any pointed to data 
–The copy constructor is implicitly called in initialization situations and makes a deep copy of the dynamic data in a different memory location
constData Members
constData Members 
•Specify object not modifiable 
•Compiler error if attempting to modify const object 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
constTime T1; // dealcaring cost with default constructor 
constTime T2(11,0,0); // decalring const with another constructor 
}
constData Members 
•Member function for constobject must be const 
–Can’t modify object 
•Specify constin both 
–Prototype: after parameter list 
–Definition: Before beginning left brace 
•Note! 
–Constructors and destructors can’t be const 
•Must be able to modify
constData Members 
classTime 
{public: 
Time(); 
voidSetTime(int,int,int); // set functions 
voidSetHour(int); 
voidSetMinute(inat); 
voidSetSecond(int); 
intGetHour() const; // get functions 
intGetMinute() const; 
intGetSecond() const; 
voidPrintTime1stform() const; 
voidPrintTime2ndform(); 
private: 
inthour;intminute;intsecond; 
}; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time() 
{hour = minute = second = 0; }; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() const{returnhour;}; 
intTime::GetMinute() const{returnminute;}; 
intTime::GetSecond() const{returnsecond;}; 
voidTime::PrintTime1stform ()const 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidTime::PrintTime2ndform () 
{cout << hour << ":"<< minute << ":"<< second << endl; }
constData Members 
0:20:0 
0:20:0 
0:0:0 
Press any key to continue 
voidmain() 
{ 
constTime T1;// delcaring cost with default constructor 
Time T2; 
T2.SetMinute(20);// non const -non constworking 
T2.GetHour();// non const -constworking 
// T1.SetHour(20);// const -non consterror 
T1.GetHour();// const -constworking 
T2.PrintTime1stform();// non const -constworking 
T2.PrintTime2ndform();// non const -non const working 
T1.PrintTime1stform();// const -constworking 
//T1.PrintTime2ndform();// const -non consterror 
} 
voidmain() 
{// delcaring const 
//with default constructor 
constTime T1; 
Time T2; 
} 
Everything is okay till now
constData Members 
•Initializing with member initializer list 
–Can be used for 
•all data members 
–Must be used for 
•constdata members 
•Data members that are references
constData Members 
classTime 
{public: 
Time(); 
voidSetTime(int,int,int); // set functions 
voidSetHour(int); 
voidSetMinute(int); 
voidSetSecond(int); 
intGetHour() const; // get functions 
intGetMinute() const; 
intGetSecond() const; 
voidPrintTime1stform() const; 
voidPrintTime2ndform(); 
private: 
inthour;intminute;constintsecond; 
}; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time() 
{hour = second = minute = 0;} 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
intTime::GetHour() const{returnhour;}; 
intTime::GetMinute() const{returnminute;}; 
intTime::GetSecond() const{returnsecond;}; 
voidTime::PrintTime1stform ()const 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidTime::PrintTime2ndform () 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
Compiler error, const member “second” must be initialize with member initializer list
constData Members 
classTime 
{public: 
Time(); 
voidSetTime(int,int,int); // set functions 
voidSetHour(int); 
voidSetMinute(int); 
voidSetSecond(int); 
intGetHour() const; // get functions 
intGetMinute() const; 
intGetSecond() const; 
voidPrintTime1stform() const; 
voidPrintTime2ndform(); 
private: 
inthour;intminute;constintsecond; 
}; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time():hour(0),minute(0),second(0){}; 
voidTime::SetTime(intxhour,intxminute, intxsecond) 
{SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; 
intTime::GetHour() const{returnhour;}; 
intTime::GetMinute() const{returnminute;}; 
intTime::GetSecond() const{returnsecond;}; 
voidTime::PrintTime1stform ()const 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidTime::PrintTime2ndform () 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
Compile error, function SetSecond change the const second
constData Members 
classTime 
{public: 
Time(); 
voidSetTime(int,int); // set functions 
voidSetHour(int); 
voidSetMinute(int); 
intGetHour() const; // get functions 
intGetMinute() const; 
intGetSecond() const; 
voidPrintTime1stform() const; 
voidPrintTime2ndform(); 
private: inthour;intminute;constintsecond; }; 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
Time::Time():hour(0),minute(0),second(5){}; 
voidTime::SetTime(intxhour,intxminute ) 
{SetHour(xhour);SetMinute(xminute);}; 
voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; 
voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; 
intTime::GetHour() const{returnhour;}; 
intTime::GetMinute() const{returnminute;}; 
intTime::GetSecond() const{returnsecond;}; 
voidTime::PrintTime1stform ()const 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
voidTime::PrintTime2ndform () 
{cout << hour << ":"<< minute << ":"<< second << endl; } 
2:3:5 
1:4:5 
Press any key to continue 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidmain() 
{ 
Time T1; 
T1.SetTime(2,3); 
T1.PrintTime1stform(); 
T1.SetTime(1,4); 
T1.PrintTime1stform(); 
}
Quiz
Quiz #1 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: object(); 
object(constobject& ob); 
~object(); 
voiddisplay(); 
voidChangeden(int); 
private: intnum, den;}; 
object::object() 
{cout << "constructing"<< endl;num = 0;den = 1;} 
object::object(constobject& ob) 
{cout << "copy constructing"<< endl;num = ob.num;den = ob.den;} 
object::~object() 
{cout << "destructing"<< endl; } 
voidobject::display() 
{cout << "num = "<< num << ", den = "<< den << endl;} 
voidobject::Changeden(intx ) 
{den = x; } 
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidPlayAgain(object x) 
{cout << "In function PlayAgain"<< endl;x.display();} 
voidPlay(object x) 
{cout << "In function Play"<< endl;PlayAgain(x); x.display();} 
voidmain() 
{object ob1; object ob2; 
cout << "In main, before Play"<< endl; 
ob1.display(); 
ob2.display(); 
Play (ob1); 
cout << "In main, after calling Play "<< endl; 
ob1.display(); 
ob2.display(); 
ob1.Changeden(3); 
ob2 = ob1; 
cout << "In main, after assignemet "<< endl; 
ob1.display(); 
ob2.Changeden(5); 
ob2.display(); 
}
#include<iostream> 
#include"TimeClass.h" 
usingnamespacestd; 
voidPlayAgain(object x) 
{cout << "In function PlayAgain"<< endl;x.display();} 
voidPlay(object x) 
{cout << "In function Play"<< endl;PlayAgain(x); x.display();} 
voidmain() 
{object ob1; object ob2; 
cout << "In main, before Play"<< endl; 
ob1.display(); 
ob2.display(); 
Play (ob1); 
cout << "In main, after calling Play "<< endl; 
ob1.display(); 
ob2.display(); 
ob1.Changeden(3); 
ob2 = ob1; 
cout << "In main, after assignemet "<< endl; 
ob1.display(); 
ob2.Changeden(5); 
ob2.display(); 
} 
Quiz #1 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: object(); 
object(constobject& ob); 
~object(); 
voiddisplay(); 
voidChangeden(int); 
private: intnum, den;}; 
object::object() 
{cout << "constructing"<< endl;num = 0;den = 1;} 
object::object(constobject& ob) 
{cout << "copy constructing"<< endl;num = ob.num;den = ob.den;} 
object::~object() 
{cout << "destructing"<< endl; } 
voidobject::display() 
{cout << "num = "<< num << ", den = "<< den << endl;} 
voidobject::Changeden(intx ) 
{den = x; } 
constructing 
constructing 
In main, before Play 
num = 0, den = 1 
num = 0, den = 1 
copy constructing 
In function Play 
copy constructing 
In function PlayAgain 
num = 0, den = 1 
destructing 
num = 0, den = 1 
destructing 
In main, after calling Play 
num = 0, den = 1 
num = 0, den = 1 
In main, after assignemet 
num = 0, den = 3 
num = 0, den = 5 
destructing 
destructing 
Press any key to continue
#include <iostream> 
#include "Testing.h" 
using namespace std; 
object first(1,"Global before main before CreateCrazy"); 
void CreateCrazy(); 
static object second(2,"Static Global before main after CreateCrazy"); 
void main() 
{ 
object bar(100, "in main"); 
{ 
object third (3,"in main"); 
} 
static object fourth(4, "static in main"); 
CreateCrazy(); 
object eigth(8,"after CreateCrazyin main"); 
} 
void CreateCrazy() 
{ 
object fifth(5, "In CreateCrazy"); 
static object sixth(6, "Local static in CreateCrazy"); 
object seventh(7, "In CreateCrazy"); 
} 
Quiz #2 
#include<iostream> 
usingnamespacestd; 
classobject 
{ 
public: 
object(intId, char*MsgPtr); 
~object(); 
private: 
intobjectId; 
char*message; 
}; 
object::object(intId, char*MsgPtr) 
{ 
objectId = Id; 
message = MsgPtr; 
cout << objectId << " constructor runs for "<< message << endl; 
} 
object::~object() 
{cout << objectId << " destructor runs for "<< message << endl;}
Quiz #2 
1 constructor runs for Global before main before CreateCrazy 
2 constructor runs for Static Global before main after CreateCrazy 
100 constructor runs for in main 
3 constructor runs for in main 
3 destructor runs for in main 
4 constructor runs for static in main 
5 constructor runs for In CreateCrazy 
6 constructor runs for Local static in CreateCrazy 
7 constructor runs for In CreateCrazy 
7 destructor runs for In CreateCrazy 
5 destructor runs for In CreateCrazy 
8 constructor runs for after CreateCrazy in main 
8 destructor runs for after CreateCrazy in main 
100 destructor runs for in main 
6 destructor runs for Local static in CreateCrazy 
4 destructor runs for static in main 
2 destructor runs for Static Global before main after CreateCrazy 
1 destructor runs for Global before main before CreateCrazy 
Press any key to continue 
Local Static is the last one of all time. Just the Global is destruct after it!

More Related Content

What's hot

Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17OdessaFrontend
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays kinan keshkeh
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядомAndrey Akinshin
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 

What's hot (20)

C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
C++ L10-Inheritance
C++ L10-InheritanceC++ L10-Inheritance
C++ L10-Inheritance
 
c programming
c programmingc programming
c programming
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
Unit 3
Unit 3 Unit 3
Unit 3
 
c programming
c programmingc programming
c programming
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
C++11
C++11C++11
C++11
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 

Viewers also liked

Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - ColorMohammad Shaker
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
WPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D AnimationWPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D AnimationMohammad Shaker
 
WPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationMohammad Shaker
 
WPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and TemplatesWPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and TemplatesMohammad Shaker
 
C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-UtilitiesMohammad Shaker
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Mohammad Shaker
 
C# Starter L01-Intro and Warm-up
C# Starter L01-Intro and Warm-upC# Starter L01-Intro and Warm-up
C# Starter L01-Intro and Warm-upMohammad Shaker
 

Viewers also liked (9)

C# Starter L05-LINQ
C# Starter L05-LINQC# Starter L05-LINQ
C# Starter L05-LINQ
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
WPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D AnimationWPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D Animation
 
WPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and Animation
 
WPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and TemplatesWPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and Templates
 
C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-Utilities
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 
C# Starter L01-Intro and Warm-up
C# Starter L01-Intro and Warm-upC# Starter L01-Intro and Warm-up
C# Starter L01-Intro and Warm-up
 

Similar to C++ L08-Classes Part1

lecture10.ppt fir class ibect fir c++ fr opps
lecture10.ppt fir class ibect fir c++ fr oppslecture10.ppt fir class ibect fir c++ fr opps
lecture10.ppt fir class ibect fir c++ fr oppsmanomkpsg
 
Military time and Standard time, JavaOne of the assignments given .pdf
Military time and Standard time, JavaOne of the assignments given .pdfMilitary time and Standard time, JavaOne of the assignments given .pdf
Military time and Standard time, JavaOne of the assignments given .pdfmarketing413921
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstractionHoang Nguyen
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08HUST
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.pptRohitPaul71
 
Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfaaseletronics2013
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ applicationDaniele Pallastrelli
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
 
Classes and object
Classes and objectClasses and object
Classes and objectAnkit Dubey
 

Similar to C++ L08-Classes Part1 (20)

lecture10.ppt
lecture10.pptlecture10.ppt
lecture10.ppt
 
lecture10.ppt fir class ibect fir c++ fr opps
lecture10.ppt fir class ibect fir c++ fr oppslecture10.ppt fir class ibect fir c++ fr opps
lecture10.ppt fir class ibect fir c++ fr opps
 
lecture10.ppt
lecture10.pptlecture10.ppt
lecture10.ppt
 
Military time and Standard time, JavaOne of the assignments given .pdf
Military time and Standard time, JavaOne of the assignments given .pdfMilitary time and Standard time, JavaOne of the assignments given .pdf
Military time and Standard time, JavaOne of the assignments given .pdf
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
C chap16
C chap16C chap16
C chap16
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
 
Oop rosenschein
Oop rosenscheinOop rosenschein
Oop rosenschein
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Object - Based Programming
Object - Based ProgrammingObject - Based Programming
Object - Based Programming
 
Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.ppt
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdf
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 
Lab 1 izz
Lab 1 izzLab 1 izz
Lab 1 izz
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Classes and object
Classes and objectClasses and object
Classes and object
 

More from Mohammad Shaker

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian GraduateMohammad Shaker
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyMohammad Shaker
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015Mohammad Shaker
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game DevelopmentMohammad Shaker
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesMohammad Shaker
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - TypographyMohammad Shaker
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingMohammad Shaker
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and ThreadingMohammad Shaker
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSMohammad Shaker
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsMohammad Shaker
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsMohammad Shaker
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and GamingMohammad Shaker
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / ParseMohammad Shaker
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesMohammad Shaker
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes Mohammad Shaker
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and AdaptersMohammad Shaker
 
Indie Series 03: Becoming an Indie
Indie Series 03: Becoming an IndieIndie Series 03: Becoming an Indie
Indie Series 03: Becoming an IndieMohammad Shaker
 
Indie Series 01: Intro to Games
Indie Series 01: Intro to GamesIndie Series 01: Intro to Games
Indie Series 01: Intro to GamesMohammad Shaker
 

More from Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 
Indie Series 03: Becoming an Indie
Indie Series 03: Becoming an IndieIndie Series 03: Becoming an Indie
Indie Series 03: Becoming an Indie
 
Indie Series 01: Intro to Games
Indie Series 01: Intro to GamesIndie Series 01: Intro to Games
Indie Series 01: Intro to Games
 

Recently uploaded

UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 

Recently uploaded (20)

UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 

C++ L08-Classes Part1

  • 1. C++ L08-CLASSES, P1 Programming Language Mohammad Shaker mohammadshaker.com @ZGTRShaker 2010, 11, 12, 13, 14
  • 2. OOP
  • 4. Float, double, long double C++ data types Structured Simple Address Pointer Reference enum Floating Array Struct Union Class Char, Short, int, long, bool Integral
  • 6. aClass •class –Concept •Information hiding •Prevent access to their inner workings •Encapsulation (private, public) –code •class –Is an extension of the idea of “struct” •class –User defined (programmer defined) type •Once class is defined it can be used as a type •Object of that class can be defined •No memory is allocated (like struct)
  • 7. a Class •Class package data declarations with function declarations –Thus, coupling data with behavior •Used to implement “ADT” •Examples: –Time, Complex numbers,
  • 8. Class •Type: –Time •Domain: –Any time value is a time in: Hour, minute, second •Operations: –Set the time –Print the time –Incrementing / decrementing time –Compare times •=, <, >
  • 9. Class •Members –They are the components of the class •Attributes •Behaviors methods •Class instance –Object
  • 10. Class •OOP and classes –Encapsulation –Composition –Inheritance –Reusable
  • 11. Class #include<iostream> usingnamespacestd; classMyClass { }; voidmain() { } Compile & run #include<iostream> usingnamespacestd; classMyClass { } voidmain() { } Compiler error. Missing ; #include<iostream> usingnamespacestd; classMyClass { inti; }; voidmain() { } Compile and run #include<iostream> usingnamespacestd; classMyClass { inti = 0; }; voidmain() { } Compiler error Rule: You can’t initialize a variable when you declare it in classes.
  • 12. Class •Function in classes –It can directly access any member of the class (WITHOUT PASSING IT AS PARAMETER) •Data members •Function members
  • 13. Class •private: –Default access mode –Accessible just to the functions of the class and friends •public: –Accessible wherever object of class in scope •protected: –Accessible from members of their same class and friends class and also from their derived class
  • 14. Class #include<iostream> usingnamespacestd; classTime { public: Time()// constructor { minute = second = hour = 0; } voidChangeTime(int,int,int) { hour = 12; second = 0; minute = 0; } private: inthour; intminute; intsecond; }; voidmain() {} #include<iostream> usingnamespacestd; classTime { public: Time();// constructor voidChangeTime(int,int,int); private: inthour; intminute; intsecond; }; voidmain() { }
  • 15. Class #include<iostream> usingnamespacestd; classTime { public: Time(); voidChangeTime(int,int,int); private: inthour; intminute; intsecond; }; Time::Time()// constructor { minute = second = hour = 0; } voidTime::ChangeTime(int,int,int) { hour = 12; second = 0; minute = 0; } voidmain() {} #include<iostream> usingnamespacestd; classTime { public: Time::Time(); voidTime::ChangeTime(int,int,int); private: inthour; intminute; intsecond; }; Time::Time()// constructor { minute = second = hour = 0; } voidTime::ChangeTime(int,int,int) { hour = 12; second = 0; minute = 0; } voidmain() {}
  • 16. Class #include<iostream> usingnamespacestd; classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":" << second << endl; } voidmain() {Time T; T.PrintTime(); T.ChangeTime(11,1,5); T.PrintTime(); } #include<iostream> usingnamespacestd; classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":" << second << endl; } voidmain() {Time T; T.hour = 12; T.PrintTime();T.ChangeTime(11,1,5); T.PrintTime(); } 0:0:0 11:5:1 Compiler error Attempting to access private data members
  • 17. Class #include<iostream> usingnamespacestd; classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} Time::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidmain() {Time T; T.PrintTime(); T.ChangeTime(11,1,5); T.PrintTime();} Compiler error Missing return type of the PrintTime() function
  • 18. Class classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); voidChangeHourFromOutside(int); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidTime::ChangeHourFromOutside(intx) {hour = x;} voidmain() { intTempHour = 0;Time T; cout << "Enter The Hour: "<< endl; cin >> TempHour;//5 T.PrintTime(); T.ChangeHourFromOutside(TempHour); T.PrintTime(); T.ChangeTime(11,1,5); T.PrintTime(); } Enter The Hour: 5 0:0:0 5:0:0 11:5:1 classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); voidChangeHourFromOutside(int); voidClear (); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidTime::ChangeHourFromOutside(intx) {hour = x;} voidTime::Clear () {minute = second = hour = 0; } voidmain() { intTempHour = 0;Time T; cout << "Enter The Hour: "<< endl; cin >> TempHour;//5 T.PrintTime(); T.ChangeHourFromOutside(TempHour); T.Clear(); T.PrintTime(); T.ChangeTime(11,1,5); T.PrintTime(); } Enter The Hour: 5 0:0:0 0:0:0 11:5:1
  • 19. Class classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); voidChangeHourFromOutside(int); voidClear (); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidTime::ChangeHourFromOutside(intx) {hour = x;} voidTime::Clear () {minute = second = hour = 0; } voidmain() { Time T1;Time *T2 = &T1; Time* &T3 = T2; T1.ChangeHourFromOutside(5); T1.PrintTime(); T2->PrintTime(); T3->PrintTime(); } 5:0:0 5:0:0 5:0:0 classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); voidChangeHourFromOutside(int); voidClear (); private: inthour; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidTime::ChangeHourFromOutside(intx) {hour = x;} voidTime::Clear () {minute = second = hour = 0; } voidmain() { Time T1;Time *T2 = &T1; Time &T3 = *T2; T1.ChangeHourFromOutside(5); T1.PrintTime(); T2->PrintTime(); T3.PrintTime(); } 5:0:0 5:0:0 5:0:0
  • 20. Class classTime { public: Time(); voidChangeTime(int,int,int); voidPrintTime(); voidChangeHourFromOutside(int); voidClear (); private: inthour = 9; intminute; intsecond; }; Time::Time()// constructor {minute = second = hour = 0; } voidTime::ChangeTime(intx1,intx2,intx3) {hour = x1; second = x2; minute = x3;} voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl;} voidTime::ChangeHourFromOutside(intx) {hour = x;} voidTime::Clear () {minute = second = hour = 0; } voidmain() { Time T1;Time *T2 = &T1; Time &T3 = *T2; T1.ChangeHourFromOutside(5); T1.PrintTime(); T2->PrintTime(); T3.PrintTime(); } Compiler error, can’t initialize when declaring no matter what private or public
  • 21. Class •A Getter, Get function: –Reads private data –“Query” functions •A Setter, Set function: –Modify private data –Perform a validity check before modifying private data –Notify if invalid values
  • 22. Class classTime {public: Time(); voidSetTime(int,int,int);// set functions voidSetHour(int); voidSetMinute(int); voidSetSecond(int); intGetHour();// get functions intGetMinute() ;intGetSecond(); voidPrintTime(); private: inthour;intminute;intsecond; }; Time::Time() {hour = minute = second = 0; }; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() {returnhour;}; intTime::GetMinute() {returnminute;}; intTime::GetSecond() {returnsecond;}; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } voidmain() { Time T; T.PrintTime(); T.SetHour(17); T.SetMinute(45); T.SetSecond(22); T.PrintTime(); T.SetHour(77); T.SetMinute(565); T.SetSecond(-1); T.PrintTime(); } 0:0:0 17:45:22 0:0:0 Press any key to continue
  • 23. Class •Utility functions (Helper functions) –private •Support operations of public member functions •Not intended for direct client use –Examples
  • 25. Organizing Your Classes •Implementing classes •Separating Interface from implementation •Headers (in header file) –if needed- –# ifndef Time_H –# define Time_H –// your code goes here –# endif
  • 26. Organizing Your Classes In MyMain.cpp #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T; T.PrintTime(); T.SetHour(17); T.SetMinute(45); T.SetSecond(22); T.PrintTime(); T.SetHour(77); T.SetMinute(565); T.SetSecond(-1); T.PrintTime(); } #include<iostream> usingnamespacestd; classTime { public: Time(); voidSetTime(int,int,int); voidSetHour(int); voidSetMinute(int); voidSetSecond(int); intGetHour(); intGetMinute(); intGetSecond(); voidPrintTime(); private: inthour; intminute; intsecond; }; In TimeClass.h #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time() {hour = minute = second = 0; }; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() {returnhour;}; intTime::GetMinute() {returnminute;}; intTime::GetSecond() {returnsecond;}; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } In TimeClass.cpp
  • 29. Class •Constructor –What’s it for? •Used to guarantee the initialization of data members of class –The same name as class –Called implicitly when object is created •Whether calling it is statically or dynamically •(new operator) * –NO return type –Can be overloaded –Must be declared in public section ________________________________________ * That means that we don’t need to call the constructor explicitly
  • 30. Class •Constructor –Two types: •Without parameters (Default constructor) •With parameters –When creating a class object, C++ provides its own constructor for the object •Compiler implicitly creates default constructor •The programmer should explicitly define it, why? –Coz the data otherwise wouldn’t be guaranteed to be in consistent state –And that doesn’t perform any initialization of fundamentals variables
  • 31. Class Constructor classTime { public: voidSetTime(int,int,int); voidSetHour(int);voidSetMinute(int); voidSetSecond(int); intGetHour();intGetMinute(); intGetSecond(); voidPrintTime(); private: inthour; intminute; intsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond); }; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() {returnhour;}; intTime::GetMinute() {returnminute;}; intTime::GetSecond() {returnsecond;}; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T; T.PrintTime(); T.SetHour(17); T.SetMinute(45); T.SetSecond(22); T.PrintTime(); T.SetHour(77); T.SetMinute(565); T.SetSecond(-1); T.PrintTime(); } 2486832:1588607792:2486968 17:45:22 0:0:0 Press any key to continue Cauze we didn’t write the constructor ourself so that the variables of the class hasn’t been initialized properly
  • 32. Class Constructor classTime {public: Time(); voidSetTime(int,int,int);// set functions voidSetHour(int); voidSetMinute(int); voidSetSecond(int); intGetHour();// get functions intGetMinute() ;intGetSecond(); voidPrintTime(); private: inthour;intminute;intsecond; }; Time::Time() {hour = minute = second = 0; }; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() {returnhour;}; intTime::GetMinute() {returnminute;}; intTime::GetSecond() {returnsecond;}; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } voidmain() { Time T; T.PrintTime(); T.SetHour(17); T.SetMinute(45); T.SetSecond(22); T.PrintTime(); T.SetHour(77); T.SetMinute(565); T.SetSecond(-1); T.PrintTime(); } 0:0:0 17:45:22 0:0:0 Press any key to continue
  • 34. Overloading Constructors •Constructors can be overloaded –must all have the same name as class •Overloading function in General allows you to use the same name for separate functions that have different argument lists
  • 35. Overloading Constructors #include<iostream> usingnamespacestd; classTime { public: Time(); Time(intTimeHour); voidPrintTime(); private: inthour; intminute; intsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time() {hour = minute = second = 0; }; Time::Time(intTimeHour) {hour = TimeHour; } voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T1; T1.PrintTime(); Time T2(2); T2.PrintTime(); } 0:0:0 2:1588607792:3011112 Press any key to continue
  • 36. Class –Member initializing list •Two ways to initialize member data by constructor –Code inserted in the constructor –A member initialization list •Given in the constructor definition –Not the prototype! •Follows the arguments list •Tells which member data to initialize with which arguments •So, how is the code? –Consists of »A colon followed by a comma separated list of member name argument pairs
  • 37. Overloading Constructors #include<iostream> usingnamespacestd; classTime { public: Time::Time():hour(),minute(),second(){}; Time(intTimeHour):hour(TimeHour),minute(0),second(0){};; Time(intTimeHour, intTimeMinute):hour(TimeHour),minute(TimeMinute),second(0){}; Time(intTimeHour, intTimeMinute, intTimeSecond):hour(TimeHour),minute(TimeMinute),second(TimeSecond){}; voidPrintTime(); private: inthour; intminute; intsecond; }; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T1; T1.PrintTime(); Time T2(2); T2.PrintTime(); Time T3(2,3,06); T3.PrintTime(); } 0:0:0 2:0:0 2:3:6
  • 38. Overloading Constructors #include<iostream> usingnamespacestd; classTime { public: Time::Time():hour(),minute(),second(); Time(intTimeHour):hour(TimeHour),minute(0),second(0){}; voidPrintTime(); private: inthour; intminute; intsecond; }; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } Compiler error, missing {}
  • 39. Overloading Constructors #include<iostream> usingnamespacestd; classTime { public: Time::Time():hour(),minute(),second(){}; Time(intTimeHour):hour(TimeHour),minute(0),second(0){}; voidPrintTime(); private: inthour; intminute; intsecond; }; voidTime::PrintTime() {cout << hour << ":"<< minute << ":"<< second << endl; } #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T1; T1.PrintTime(); Time T2(2); T2.PrintTime(); Time T3(2,3,06); T3.PrintTime(); } Compiler error, no oveloaded function which takes 3 arguments
  • 41. Classes Destructors •Same name as class •Preceded by tilde (~) •No arguments •No return value •Can’t be overloaded –Once only •When is it called? –When the object is destroyed •Termination housekeeping •new delete •If no explicit destructor was declared, –Compiler creates “Empty destructor”
  • 42. Constructors VS Destructors •Orders of constructor destructor calls –Depends on scope –Generally, destructor are called in reverse order of constructor call
  • 43. Constructors VS Destructors •Global scope object: –Constructors: •Before any other function (including main!) –Destructors: •When –main terminates –exit function is called •Not called with abort
  • 44. Constructors VS Destructors •Automatic local object: –Constructors: •When object is defined –Each time entering scope –Destructors: •When –Objects leave scope •Not called with abort or exit
  • 45. Constructors VS Destructors •static local object: –Constructors: •Exactly once •When the execution reaches point where the object is defined –Destructors: •When –main terminates –exit function is called •Not called with abort
  • 46. Class Constructor #include<iostream> usingnamespacestd; classobject { public: object(intId, char*MsgPtr); ~object(); private: intobjectId; char*message; }; object::object(intId, char*MsgPtr) { objectId = Id; message = MsgPtr; cout << objectId << " constructor runs for "<< message << endl; } object::~object() { cout << objectId << " destructor runs for "<< message << endl; } #include<iostream> #include"TimeClass.h" usingnamespacestd; object first(1,"Global before main before CreateCrazy"); voidCreateCrazy(); voidmain() { staticobject fourth(4, "static in main"); CreateCrazy(); } voidCreateCrazy() { object fifth(5, "In CreateCrazy"); } 1 constructor runs for Global before main before CreateCrazy 4 constructor runs for static in main 5 constructor runs for In CreateCrazy 5 destructor runs for In CreateCrazy 4 destructor runs for static in main 1 destructor runs for Global before main before CreateCrazy Press any key to continue
  • 48. Copy Constructor •Special member functions –That’s implicitly called in the following 3 situations •Object used to initialize another object –obj1(obj2) •Passing an object arguments by value to another object •Returning a temporary object as the return value of a function
  • 49. Copy Constructor •C++ provides its own implicitly copy constructor –Overloaded constructor –Has no return value –Take only arguments as a reference to an object of the same class –The compiler provides a copy whose signature is: –Class_Name::Class_Name (const Class_Name&) –When an object is passed to a function, a simple bitwise (exact) copy of that object is made and given to the function
  • 50. Copy Constructor •Assignment “=” –Assign object to object –Is done by •Each member in the first object is copied individually to the same member in the second one •Done to the object that are value arguments
  • 51. Copy Constructor #include<iostream> usingnamespacestd; classobject { public: object(); object(constobject& ob); ~object(); voiddisplay(); private: intnum, den;}; object::object() {cout << "constructing"<< endl; num = 0; den = 1;} object::object(constobject& ob) {cout << "copy constructing"<< endl; num = ob.num; den = ob.den;} object::~object() {cout << "destructing"<< endl;} voidobject::display() {cout << "num = "<< num << ", den = "<< den << endl;} #include<iostream> #include"TimeClass.h" usingnamespacestd; voidPlay(object x) { cout << "In function Play"<< endl; x.display(); } voidmain() { object ob1; object ob2; cout << "In main, before Play"<< endl; ob1.display(); ob2.display(); Play (ob1); cout << "In main, after calling Play "<< endl; ob1.display(); ob2.display(); ob2 = ob1; cout << "In main, after assignemet "<< endl; ob1.display(); ob2.display(); }
  • 52. Copy Constructor #include<iostream> usingnamespacestd; classobject { public: object(); object(constobject& ob); ~object(); voiddisplay(); private: intnum, den;}; object::object() {cout << "constructing"<< endl; num = 0; den = 1;} object::object(constobject& ob) {cout << "copy constructing"<< endl; num = ob.num; den = ob.den;} object::~object() {cout << "destructing"<< endl;} voidobject::display() {cout << "num = "<< num << ", den = "<< den << endl;} #include<iostream> #include"TimeClass.h" usingnamespacestd; voidPlay(object x) { cout << "In function Play"<< endl; x.display(); } voidmain() { object ob1; object ob2; cout << "In main, before Play"<< endl; ob1.display(); ob2.display(); Play (ob1); cout << "In main, after calling Play "<< endl; ob1.display(); ob2.display(); ob2 = ob1; cout << "In main, after assignemet "<< endl; ob1.display(); ob2.display(); } constructing constructing In main, before Play num = 0, den = 1 num = 0, den = 1 copy constructing In function Play num = 0, den = 1 destructing In main, after calling Play num = 0, den = 1 num = 0, den = 1 In main, after assignemet num = 0, den = 1 num = 0, den = 1 destructing destructing Press any key to continue
  • 54. Shallow copy VS Deep Copy •C++,by default, use shallow copy for initializations and assignments •With shallow copy, if the object contains a pointer to allocated memory –The copy will also point to the memory as does the original object –Deleting the original object may cause the copied object to incorrectly disappear!
  • 55. Shallow copy VS Deep Copy •If the class data points to a dynamic data –You should write your own copy constructor to create a “deep copy” of the dynamic data –A deep copy copies not only the class data members, but also makes a separate stored copy of any pointed to data –The copy constructor is implicitly called in initialization situations and makes a deep copy of the dynamic data in a different memory location
  • 57. constData Members •Specify object not modifiable •Compiler error if attempting to modify const object #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { constTime T1; // dealcaring cost with default constructor constTime T2(11,0,0); // decalring const with another constructor }
  • 58. constData Members •Member function for constobject must be const –Can’t modify object •Specify constin both –Prototype: after parameter list –Definition: Before beginning left brace •Note! –Constructors and destructors can’t be const •Must be able to modify
  • 59. constData Members classTime {public: Time(); voidSetTime(int,int,int); // set functions voidSetHour(int); voidSetMinute(inat); voidSetSecond(int); intGetHour() const; // get functions intGetMinute() const; intGetSecond() const; voidPrintTime1stform() const; voidPrintTime2ndform(); private: inthour;intminute;intsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time() {hour = minute = second = 0; }; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() const{returnhour;}; intTime::GetMinute() const{returnminute;}; intTime::GetSecond() const{returnsecond;}; voidTime::PrintTime1stform ()const {cout << hour << ":"<< minute << ":"<< second << endl; } voidTime::PrintTime2ndform () {cout << hour << ":"<< minute << ":"<< second << endl; }
  • 60. constData Members 0:20:0 0:20:0 0:0:0 Press any key to continue voidmain() { constTime T1;// delcaring cost with default constructor Time T2; T2.SetMinute(20);// non const -non constworking T2.GetHour();// non const -constworking // T1.SetHour(20);// const -non consterror T1.GetHour();// const -constworking T2.PrintTime1stform();// non const -constworking T2.PrintTime2ndform();// non const -non const working T1.PrintTime1stform();// const -constworking //T1.PrintTime2ndform();// const -non consterror } voidmain() {// delcaring const //with default constructor constTime T1; Time T2; } Everything is okay till now
  • 61. constData Members •Initializing with member initializer list –Can be used for •all data members –Must be used for •constdata members •Data members that are references
  • 62. constData Members classTime {public: Time(); voidSetTime(int,int,int); // set functions voidSetHour(int); voidSetMinute(int); voidSetSecond(int); intGetHour() const; // get functions intGetMinute() const; intGetSecond() const; voidPrintTime1stform() const; voidPrintTime2ndform(); private: inthour;intminute;constintsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time() {hour = second = minute = 0;} voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; intTime::GetHour() const{returnhour;}; intTime::GetMinute() const{returnminute;}; intTime::GetSecond() const{returnsecond;}; voidTime::PrintTime1stform ()const {cout << hour << ":"<< minute << ":"<< second << endl; } voidTime::PrintTime2ndform () {cout << hour << ":"<< minute << ":"<< second << endl; } Compiler error, const member “second” must be initialize with member initializer list
  • 63. constData Members classTime {public: Time(); voidSetTime(int,int,int); // set functions voidSetHour(int); voidSetMinute(int); voidSetSecond(int); intGetHour() const; // get functions intGetMinute() const; intGetSecond() const; voidPrintTime1stform() const; voidPrintTime2ndform(); private: inthour;intminute;constintsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time():hour(0),minute(0),second(0){}; voidTime::SetTime(intxhour,intxminute, intxsecond) {SetHour(xhour);SetMinute(xminute);SetSecond(xsecond);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; voidTime::SetSecond(ints) { second = (s>=0 && s<60)? s: 0; }; intTime::GetHour() const{returnhour;}; intTime::GetMinute() const{returnminute;}; intTime::GetSecond() const{returnsecond;}; voidTime::PrintTime1stform ()const {cout << hour << ":"<< minute << ":"<< second << endl; } voidTime::PrintTime2ndform () {cout << hour << ":"<< minute << ":"<< second << endl; } Compile error, function SetSecond change the const second
  • 64. constData Members classTime {public: Time(); voidSetTime(int,int); // set functions voidSetHour(int); voidSetMinute(int); intGetHour() const; // get functions intGetMinute() const; intGetSecond() const; voidPrintTime1stform() const; voidPrintTime2ndform(); private: inthour;intminute;constintsecond; }; #include<iostream> #include"TimeClass.h" usingnamespacestd; Time::Time():hour(0),minute(0),second(5){}; voidTime::SetTime(intxhour,intxminute ) {SetHour(xhour);SetMinute(xminute);}; voidTime::SetHour(inth) { hour = (h>=0 && h<24)? h: 0; }; voidTime::SetMinute(intm) { minute = (m>=0 && m<60)? m: 0; }; intTime::GetHour() const{returnhour;}; intTime::GetMinute() const{returnminute;}; intTime::GetSecond() const{returnsecond;}; voidTime::PrintTime1stform ()const {cout << hour << ":"<< minute << ":"<< second << endl; } voidTime::PrintTime2ndform () {cout << hour << ":"<< minute << ":"<< second << endl; } 2:3:5 1:4:5 Press any key to continue #include<iostream> #include"TimeClass.h" usingnamespacestd; voidmain() { Time T1; T1.SetTime(2,3); T1.PrintTime1stform(); T1.SetTime(1,4); T1.PrintTime1stform(); }
  • 65. Quiz
  • 66. Quiz #1 #include<iostream> usingnamespacestd; classobject { public: object(); object(constobject& ob); ~object(); voiddisplay(); voidChangeden(int); private: intnum, den;}; object::object() {cout << "constructing"<< endl;num = 0;den = 1;} object::object(constobject& ob) {cout << "copy constructing"<< endl;num = ob.num;den = ob.den;} object::~object() {cout << "destructing"<< endl; } voidobject::display() {cout << "num = "<< num << ", den = "<< den << endl;} voidobject::Changeden(intx ) {den = x; } #include<iostream> #include"TimeClass.h" usingnamespacestd; voidPlayAgain(object x) {cout << "In function PlayAgain"<< endl;x.display();} voidPlay(object x) {cout << "In function Play"<< endl;PlayAgain(x); x.display();} voidmain() {object ob1; object ob2; cout << "In main, before Play"<< endl; ob1.display(); ob2.display(); Play (ob1); cout << "In main, after calling Play "<< endl; ob1.display(); ob2.display(); ob1.Changeden(3); ob2 = ob1; cout << "In main, after assignemet "<< endl; ob1.display(); ob2.Changeden(5); ob2.display(); }
  • 67. #include<iostream> #include"TimeClass.h" usingnamespacestd; voidPlayAgain(object x) {cout << "In function PlayAgain"<< endl;x.display();} voidPlay(object x) {cout << "In function Play"<< endl;PlayAgain(x); x.display();} voidmain() {object ob1; object ob2; cout << "In main, before Play"<< endl; ob1.display(); ob2.display(); Play (ob1); cout << "In main, after calling Play "<< endl; ob1.display(); ob2.display(); ob1.Changeden(3); ob2 = ob1; cout << "In main, after assignemet "<< endl; ob1.display(); ob2.Changeden(5); ob2.display(); } Quiz #1 #include<iostream> usingnamespacestd; classobject { public: object(); object(constobject& ob); ~object(); voiddisplay(); voidChangeden(int); private: intnum, den;}; object::object() {cout << "constructing"<< endl;num = 0;den = 1;} object::object(constobject& ob) {cout << "copy constructing"<< endl;num = ob.num;den = ob.den;} object::~object() {cout << "destructing"<< endl; } voidobject::display() {cout << "num = "<< num << ", den = "<< den << endl;} voidobject::Changeden(intx ) {den = x; } constructing constructing In main, before Play num = 0, den = 1 num = 0, den = 1 copy constructing In function Play copy constructing In function PlayAgain num = 0, den = 1 destructing num = 0, den = 1 destructing In main, after calling Play num = 0, den = 1 num = 0, den = 1 In main, after assignemet num = 0, den = 3 num = 0, den = 5 destructing destructing Press any key to continue
  • 68. #include <iostream> #include "Testing.h" using namespace std; object first(1,"Global before main before CreateCrazy"); void CreateCrazy(); static object second(2,"Static Global before main after CreateCrazy"); void main() { object bar(100, "in main"); { object third (3,"in main"); } static object fourth(4, "static in main"); CreateCrazy(); object eigth(8,"after CreateCrazyin main"); } void CreateCrazy() { object fifth(5, "In CreateCrazy"); static object sixth(6, "Local static in CreateCrazy"); object seventh(7, "In CreateCrazy"); } Quiz #2 #include<iostream> usingnamespacestd; classobject { public: object(intId, char*MsgPtr); ~object(); private: intobjectId; char*message; }; object::object(intId, char*MsgPtr) { objectId = Id; message = MsgPtr; cout << objectId << " constructor runs for "<< message << endl; } object::~object() {cout << objectId << " destructor runs for "<< message << endl;}
  • 69. Quiz #2 1 constructor runs for Global before main before CreateCrazy 2 constructor runs for Static Global before main after CreateCrazy 100 constructor runs for in main 3 constructor runs for in main 3 destructor runs for in main 4 constructor runs for static in main 5 constructor runs for In CreateCrazy 6 constructor runs for Local static in CreateCrazy 7 constructor runs for In CreateCrazy 7 destructor runs for In CreateCrazy 5 destructor runs for In CreateCrazy 8 constructor runs for after CreateCrazy in main 8 destructor runs for after CreateCrazy in main 100 destructor runs for in main 6 destructor runs for Local static in CreateCrazy 4 destructor runs for static in main 2 destructor runs for Static Global before main after CreateCrazy 1 destructor runs for Global before main before CreateCrazy Press any key to continue Local Static is the last one of all time. Just the Global is destruct after it!