SlideShare a Scribd company logo
CLASSES and
CONSTRUCTORS
Structure vs. Classes
(Similarities)
Both used to model objects with:
 different attributes (characteristics)
represented as data members (also called
fields or instance variables)
 Thus, both used to process non-
homogeneous data sets.
 Both have members function and data;
what's difference(s) then?
Structs vs Classes Differences
 C does not provide classes (struct only);
 C++ provides both structs and classes.
 Members of a struct by default are public can
be accessed outside the struct by using the dot
operator (or pointer->)
 Members of a class by default are private
cannot be accessed outside the class but can
be explicitly declared public
C++ Classes
 C++'s structs and classes model objects that have:
 Attributes (characteristics) represented as data members
 Operations (behaviors) represented as function
members (methods).
 new style of programming : Object-Oriented
 Objects are self-contained,
 Associated with their own operations the I can do it
myself principle
 rather than being passed as a parameter to an external
function for operations on them and sent back.
Conventions on Defining a Class
 Data members are normally placed in the private section of a class;
 Function members in the public section.
 Some programmers prefer to put the private section first
 Use the default access for classes
 Omit the private: specifier
 Example1: Default and Explicit Sections
class ClassName
{
// private by default
Declarations of private members
:
public: // default changed: explicitly public
Declarations of public members
};
 Other programmers put the public "interface" of the class first
 and the "hidden" private details last.
 Example2: Separate Sections
 class ClassName
 {
 public://"interface" of class given 1st
 Declarations of public members
 :
 private:
 Declarations of private members
 };
 Although not common (poor technique),
 a class may have several private and public sections;
 the keywords private: and public: mark the beginning of each.
Constructors
 Like ordinary variables class object is initialized by
initializing its data members. Provided all members are
public, object may be initialized using a comma-separated
list of values (as usual) like:
class Student {
public:
int rollno;
char *name;
};
// Explicit member initialization (by Programmer)
Student x = {0, "Muhammed Ali Jinnah"};
Auto Initialization and Clean Up
 In C++, declaration and definition/initialization are unified
concepts
 Class designer can guarantee initialization of every object
by providing a special function called the constructor.
 If a class has a constructor, the compiler automatically
calls that constructor at the time of its creation, before
user get their hands on the object.
 The constructor call isn’t even an option for the client
programmer; it is performed by the compiler at the point
the object is defined.
 The constructor in C++ allows you to guarantee that
variables of your new data type (“objects of your class”)
will always be properly initialized.
 If your objects also require some sort of
cleanup, you can guarantee that this cleanup
will always happen with the C++ destructor.
 Both the constructor and destructor are very
unusual types of functions: They have no
return value.
 This is distinctly different from a void return
value, where the function returns nothing but
you still have the option to make it something
else. Constructors and destructors return
nothing and you don’t have an option.
Class Constructor Properties
 Names are always the same as the class name.
 Initialize the data members of an object with default
values or as arguments
 do not return a value
 have no return type
 called whenever an object is declared to initialize its
data member
 If no constructor is given in the class, compiler
supplies a default
 A default constructor is one that is used when the
declaration of an object contains no initial values (i.e.
no parameters)
class Date
{
int day,month,year;
public:
Date();// default constructor
Date(int,int,int);//constructor with 3 parametrs
Date(char d[20]); //constructor with 1 parametr
~Date(); //destructor
void SetDate(int,int,int);
void PrintDate();
void IncDate();
};
Example
Date::Date()
{
cout<<"Look i am being created by default
constructor"<<endl;
}
Date::Date(int d,int m,int y):day(d),month(m),year(y)
{
cout<<"Look i am being created by 3 argument
constructor"<<endl;
}
Date::Date(char d[20])
{
cout<<"Look i am being created by string
constructor"<<endl;
}
Date::~Date()
{
cout<<"Oh My God i am dead"<<endl;
}
void Date::SetDate(int d,int m,int y)
{
day = d;
month = m;
year = y;
}
void Date::PrintDate()
{
cout<<"Date : "<<day<<"/"<<month<<"/"<<year<<endl;
}
void Date::IncDate()
{
day++;
if (day > 30)
{
day = 1;
month++;
if (month > 12)
{
month = 1;
year++;
}
}
}
void f1()
{
cout<<"We have entered in function f1
"<<endl;
Date today;
today.SetDate(23,2,2006);
cout<<"Today Date is : ";
today.PrintDate();
today.IncDate();
cout<<"Oh its a new day : ";
today.PrintDate();
cout<<"We are exiting function f1:"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Date birthday(30,4,1999);
f1();
}
classes and constructors lec 03 & 04.ppt
Using Default Arguments with
Constructors
 Constructors
• Can specify default arguments
• Default constructors
• Defaults all arguments
OR
• Explicitly requires no arguments
• Can be invoked with no arguments
• Only one per class
// Time abstract data type definition
class Time {
public:
Time( int = 0, int = 0, int = 0); // default constructor
void setTime( int, int, int ); // set hour, minute, second
void printUniversal(); // print universal-time format
void printStandard(); // print standard-time format
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}; // end class Time
Example
// Member-function definitions for class Time.
#include <iostream>
// include definition of class Time from time2.h
#include "time2.h"
// Time constructor initializes each data member to zero;
// ensures all Time objects start in a consistent state
Time::Time( int hr, int min, int sec )
{
setTime( hr, min, sec ); // validate and set time
} // end Time constructor
// set new Time value using universal time, perform validity
// checks on the data values and set invalid values to zero
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
} // end function setTime
// print Time in universal format
void Time::printUniversal()
{
cout << setfill( '0' ) << setw( 2 ) << hour << ":“
<< setw( 2 ) << minute << ":“
<< setw( 2 ) << second;
} // end function printUniversal
// print Time in standard format
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % )
<< ":" << setfill( '0' ) << setw( 2 ) << minute
<< ":" << setw( 2 ) << second
<< ( hour < 12 ? " AM" : " PM" );
} // end function printStandard
#include "time2.h"
int main()
{
Time t1; // all arguments defaulted
Time t2( 2 ); // minute and second defaulted
Time t3( 21, 34 ); // second defaulted
Time t4( 12, 25, 42 ); // all values specified
Time t5( 27, 74, 99 ); // all bad values specified
cout << "Constructed with:nn"
<< "all default arguments:n ";
t1.printUniversal(); // 00:00:00
cout << "n ";
t1.printStandard(); // 12:00:00 AM
cout << "nnhour specified; default minute and second:n ";
t2.printUniversal(); // 02:00:00
cout << "n ";
t2.printStandard(); // 2:00:00 AM
cout << "nnhour and minute specified; default second:n ";
t3.printUniversal(); // 21:34:00
cout << "n ";
t3.printStandard(); // 9:34:00 PM
cout << "nnhour, minute, and second specified:n ";
t4.printUniversal(); // 12:25:42
cout << "n ";
t4.printStandard(); // 12:25:42 PM
cout << "nnall invalid values specified:n ";
t5.printUniversal(); // 00:00:00
cout << "n ";
t5.printStandard(); // 12:00:00 AM
cout << endl;
return 0;
}
Output
Destructors
 Destructors
• Special member function
• Same name as class
• Preceded with tilde (~)
• No arguments
• No return value
• Cannot be overloaded
• Performs “termination housekeeping”
• Before system reclaims object’s memory
• Reuse memory for new objects
• No explicit destructor
• Compiler creates “empty” destructor”
When Constructors and
Destructors Are Called
 Constructors and destructors
• Called implicitly by compiler
 Order of function calls
• Depends on order of execution
• When execution enters and exits scope of objects
• Generally, destructor calls reverse order of
constructor calls
When Constructors and
Destructors Are Called
 Order of constructor, destructor function calls
• Global scope objects
• Constructors
• Before any other function (including main)
• Destructors
• When main terminates (or exit function called)
• Not called if program terminates with abort
• Automatic local objects
• Constructors
• When objects defined
• Each time execution enters scope
• Destructors
• When objects leave scope
• Execution exits block in which object defined
• Not called if program ends with exit or abort
Example
// declaration for a destructor:
class Y
{
public:
~Y();
};
classes and constructors lec 03 & 04.ppt
classes and constructors lec 03 & 04.ppt
Thank You
Ad

More Related Content

Similar to classes and constructors lec 03 & 04.ppt (20)

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
Aneeskhan326131
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Pranali Chaudhari
 
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
aaseletronics2013
 
Introduction to C Programming -Lecture 4
Introduction to C Programming -Lecture 4Introduction to C Programming -Lecture 4
Introduction to C Programming -Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
classes and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggfclasses and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggf
gurpreetk8199
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
रमन सनौरिया
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
constructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptxconstructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
Constructors & Destructors in C++ Simplified
Constructors & Destructors in C++ SimplifiedConstructors & Destructors in C++ Simplified
Constructors & Destructors in C++ Simplified
TaseenTariq1
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
Hoang Nguyen
 
C chap16
C chap16C chap16
C chap16
akkaraikumar
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
babuk110
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
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
aaseletronics2013
 
classes and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggfclasses and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggf
gurpreetk8199
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
constructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptxconstructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
Constructors & Destructors in C++ Simplified
Constructors & Destructors in C++ SimplifiedConstructors & Destructors in C++ Simplified
Constructors & Destructors in C++ Simplified
TaseenTariq1
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
Hoang Nguyen
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
babuk110
 

Recently uploaded (20)

Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Ad

classes and constructors lec 03 & 04.ppt

  • 2. Structure vs. Classes (Similarities) Both used to model objects with:  different attributes (characteristics) represented as data members (also called fields or instance variables)  Thus, both used to process non- homogeneous data sets.  Both have members function and data; what's difference(s) then?
  • 3. Structs vs Classes Differences  C does not provide classes (struct only);  C++ provides both structs and classes.  Members of a struct by default are public can be accessed outside the struct by using the dot operator (or pointer->)  Members of a class by default are private cannot be accessed outside the class but can be explicitly declared public
  • 4. C++ Classes  C++'s structs and classes model objects that have:  Attributes (characteristics) represented as data members  Operations (behaviors) represented as function members (methods).  new style of programming : Object-Oriented  Objects are self-contained,  Associated with their own operations the I can do it myself principle  rather than being passed as a parameter to an external function for operations on them and sent back.
  • 5. Conventions on Defining a Class  Data members are normally placed in the private section of a class;  Function members in the public section.  Some programmers prefer to put the private section first  Use the default access for classes  Omit the private: specifier  Example1: Default and Explicit Sections class ClassName { // private by default Declarations of private members : public: // default changed: explicitly public Declarations of public members };
  • 6.  Other programmers put the public "interface" of the class first  and the "hidden" private details last.  Example2: Separate Sections  class ClassName  {  public://"interface" of class given 1st  Declarations of public members  :  private:  Declarations of private members  };  Although not common (poor technique),  a class may have several private and public sections;  the keywords private: and public: mark the beginning of each.
  • 7. Constructors  Like ordinary variables class object is initialized by initializing its data members. Provided all members are public, object may be initialized using a comma-separated list of values (as usual) like: class Student { public: int rollno; char *name; }; // Explicit member initialization (by Programmer) Student x = {0, "Muhammed Ali Jinnah"};
  • 8. Auto Initialization and Clean Up  In C++, declaration and definition/initialization are unified concepts  Class designer can guarantee initialization of every object by providing a special function called the constructor.  If a class has a constructor, the compiler automatically calls that constructor at the time of its creation, before user get their hands on the object.  The constructor call isn’t even an option for the client programmer; it is performed by the compiler at the point the object is defined.  The constructor in C++ allows you to guarantee that variables of your new data type (“objects of your class”) will always be properly initialized.
  • 9.  If your objects also require some sort of cleanup, you can guarantee that this cleanup will always happen with the C++ destructor.  Both the constructor and destructor are very unusual types of functions: They have no return value.  This is distinctly different from a void return value, where the function returns nothing but you still have the option to make it something else. Constructors and destructors return nothing and you don’t have an option.
  • 10. Class Constructor Properties  Names are always the same as the class name.  Initialize the data members of an object with default values or as arguments  do not return a value  have no return type  called whenever an object is declared to initialize its data member  If no constructor is given in the class, compiler supplies a default  A default constructor is one that is used when the declaration of an object contains no initial values (i.e. no parameters)
  • 11. class Date { int day,month,year; public: Date();// default constructor Date(int,int,int);//constructor with 3 parametrs Date(char d[20]); //constructor with 1 parametr ~Date(); //destructor void SetDate(int,int,int); void PrintDate(); void IncDate(); }; Example
  • 12. Date::Date() { cout<<"Look i am being created by default constructor"<<endl; } Date::Date(int d,int m,int y):day(d),month(m),year(y) { cout<<"Look i am being created by 3 argument constructor"<<endl; } Date::Date(char d[20]) { cout<<"Look i am being created by string constructor"<<endl; } Date::~Date() { cout<<"Oh My God i am dead"<<endl; }
  • 13. void Date::SetDate(int d,int m,int y) { day = d; month = m; year = y; } void Date::PrintDate() { cout<<"Date : "<<day<<"/"<<month<<"/"<<year<<endl; } void Date::IncDate() { day++; if (day > 30) { day = 1; month++; if (month > 12) { month = 1; year++; } } }
  • 14. void f1() { cout<<"We have entered in function f1 "<<endl; Date today; today.SetDate(23,2,2006); cout<<"Today Date is : "; today.PrintDate(); today.IncDate(); cout<<"Oh its a new day : "; today.PrintDate(); cout<<"We are exiting function f1:"<<endl; } int _tmain(int argc, _TCHAR* argv[]) { Date birthday(30,4,1999); f1(); }
  • 16. Using Default Arguments with Constructors  Constructors • Can specify default arguments • Default constructors • Defaults all arguments OR • Explicitly requires no arguments • Can be invoked with no arguments • Only one per class
  • 17. // Time abstract data type definition class Time { public: Time( int = 0, int = 0, int = 0); // default constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format private: int hour; // 0 - 23 (24-hour clock format) int minute; // 0 - 59 int second; // 0 - 59 }; // end class Time Example
  • 18. // Member-function definitions for class Time. #include <iostream> // include definition of class Time from time2.h #include "time2.h" // Time constructor initializes each data member to zero; // ensures all Time objects start in a consistent state Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); // validate and set time } // end Time constructor
  • 19. // set new Time value using universal time, perform validity // checks on the data values and set invalid values to zero void Time::setTime( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; } // end function setTime // print Time in universal format void Time::printUniversal() { cout << setfill( '0' ) << setw( 2 ) << hour << ":“ << setw( 2 ) << minute << ":“ << setw( 2 ) << second; } // end function printUniversal
  • 20. // print Time in standard format void Time::printStandard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard
  • 21. #include "time2.h" int main() { Time t1; // all arguments defaulted Time t2( 2 ); // minute and second defaulted Time t3( 21, 34 ); // second defaulted Time t4( 12, 25, 42 ); // all values specified Time t5( 27, 74, 99 ); // all bad values specified cout << "Constructed with:nn" << "all default arguments:n "; t1.printUniversal(); // 00:00:00 cout << "n "; t1.printStandard(); // 12:00:00 AM
  • 22. cout << "nnhour specified; default minute and second:n "; t2.printUniversal(); // 02:00:00 cout << "n "; t2.printStandard(); // 2:00:00 AM cout << "nnhour and minute specified; default second:n "; t3.printUniversal(); // 21:34:00 cout << "n "; t3.printStandard(); // 9:34:00 PM cout << "nnhour, minute, and second specified:n "; t4.printUniversal(); // 12:25:42 cout << "n "; t4.printStandard(); // 12:25:42 PM cout << "nnall invalid values specified:n "; t5.printUniversal(); // 00:00:00 cout << "n "; t5.printStandard(); // 12:00:00 AM cout << endl; return 0; }
  • 24. Destructors  Destructors • Special member function • Same name as class • Preceded with tilde (~) • No arguments • No return value • Cannot be overloaded • Performs “termination housekeeping” • Before system reclaims object’s memory • Reuse memory for new objects • No explicit destructor • Compiler creates “empty” destructor”
  • 25. When Constructors and Destructors Are Called  Constructors and destructors • Called implicitly by compiler  Order of function calls • Depends on order of execution • When execution enters and exits scope of objects • Generally, destructor calls reverse order of constructor calls
  • 26. When Constructors and Destructors Are Called  Order of constructor, destructor function calls • Global scope objects • Constructors • Before any other function (including main) • Destructors • When main terminates (or exit function called) • Not called if program terminates with abort • Automatic local objects • Constructors • When objects defined • Each time execution enters scope • Destructors • When objects leave scope • Execution exits block in which object defined • Not called if program ends with exit or abort
  • 27. Example // declaration for a destructor: class Y { public: ~Y(); };
  翻译: