SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Constructors and Destructors


Objectives
In this lesson, you will learn to:
 Identify the need for constructors
 Declare constructors
 Identify the need for destructors
 Declare destructors
 Use scope resolution operator
 Use constructors with parameters
 Invoke member functions by using:
     The call by value method

©NIIT                                  OOPS/Lesson 7/Slide 1 of 25
Constructors and Destructors


Objectives (Contd.)
     The call by reference method
        ® Using   alias
        ® Using   pointer




©NIIT                                OOPS/Lesson 7/Slide 2 of 25
Constructors and Destructors


Constructors
 Are used to initialize the member variables of the
  class when the objects of the class are created
 Must have the same name as that of class name
 Cannot return any value, not even a void type
 Class can have more than one constructors defined in
  it (known as overloaded constructors)
 Default constructors accept no parameters and are
  automatically invoked by the compiler




©NIIT                                OOPS/Lesson 7/Slide 3 of 25
Constructors and Destructors


Need for Constructors
 To initialize a member variable at the time of
  declaration




©NIIT                                 OOPS/Lesson 7/Slide 4 of 25
Constructors and Destructors

Declaration of Constructors
 Example:
  class Calculator
  {
  private:
     int number1, number2, tot;
  public:
     ...
     Calculator()
     {
     number1 = number2 = tot = 0;
     cout  Constructor invoked endl;
     }
  };

©NIIT                          OOPS/Lesson 7/Slide 5 of 25
Constructors and Destructors


Destructors
 Are used to de-initialize the objects when they are
  destroyed
 Are used to clear memory space occupied by a data
  member when an object goes out of scope
 Must have the same name as that of the class,
  preceded by a ~ (For example: ~Calculator())
 Are automatically invoked
 Can also be explicitly invoked when required
 Cannot be overloaded


©NIIT                                OOPS/Lesson 7/Slide 6 of 25
Constructors and Destructors


Need for Destructors
 To de-initialize the objects when they are destroyed
 To clear memory space occupied by a data member
  when an object goes out of scope




©NIIT                                OOPS/Lesson 7/Slide 7 of 25
Constructors and Destructors

Declaration of Destructors
 Example:
  /* This Code Shows The Use Of Destructor
  In The Calculator Class */
  class Calculator
  {
  private:
     int number1, number2, tot;
  public:
     ...
     ~Calculator()    //Body Of The
                      //Destructor
     {
     number1 = number2 = tot = 0;
     }
  };
©NIIT                          OOPS/Lesson 7/Slide 8 of 25
Constructors and Destructors

Just a Minute…
Given is a code snippet for the main() function of a
program. How would you ensure that the following tasks
are accomplished when the program is executed:
    1. The member variables are initialized with zero
    2. On exit or termination of the program the following
       message is displayed : “Bye Folks!!! Have a Nice
       Time”
    #include iostream
    int main()
    {
      Number num1;num1.disp();
    }
    Hint: The Number class has only one member
variable
©NIIT
                            myNum. OOPS/Lesson 7/Slide 9 of   25
Constructors and Destructors

Scope Resolution Operator (::)
 Is used to define member functions outside the class
  definition therefore making the class definition more
  readable
 Example:
   class calculator
   {
   public:
     void input();
   };
    void calculator::input ()
  {…}

©NIIT                               OOPS/Lesson 7/Slide 10 of 25
Constructors and Destructors


Constructors with Parameters
 Allow member variables of the class to be initialized
  with user supplied values from main() function also
  called parameters
Example
   class calculate
   {
   private:
   int num1,num2,total;
   public:
     calculate(int, int);
        };
©NIIT                                OOPS/Lesson 7/Slide 11 of 25
Constructors and Destructors


Constructors with Parameters (Contd.)
calculate::calculate(int x, int y)
{
 num1=x;num2=y;
 total=0;
}
 int main()
{//Accept values in two variable var1
 //var2
calculate c1(var1,var2);
}

©NIIT                          OOPS/Lesson 7/Slide 12 of 25
Constructors and Destructors


Invoking Member Functions
 By using call by value
 By using call by reference




©NIIT                          OOPS/Lesson 7/Slide 13 of 25
Constructors and Destructors


Call by Value
 Is useful when the function does not need to modify
  the values of the original variables
 Does not affect the values of the variables in caller
  functions




©NIIT                                OOPS/Lesson 7/Slide 14 of 25
Constructors and Destructors

Problem Statement 5.P.1
Predict the Output:
   #include iostream
   void square(int);
   class functionCall
   {
      int number;
      public:
      functionCall();
   };
   functionCall::functionCall()
   {
      number=10;square(number);
   }
©NIIT                          OOPS/Lesson 7/Slide 15 of 25
Constructors and Destructors


Problem Statement 5.P.1 (Contd.)
    void square(int num)
    {
      coutnumendl;
        num *= num; //This Expression Is
        //Resolved As num = num * num
        cout  num  endl;
    }
    int main()
    {
      functionCall f1;
      return 0;
    }

©NIIT                          OOPS/Lesson 7/Slide 16 of 25
Constructors and Destructors


Call by Reference
 Is implemented by using
     An alias
     Pointers




©NIIT                          OOPS/Lesson 7/Slide 17 of 25
Constructors and Destructors


Call by Reference (Contd.)
 Using an alias
     The same variable can be referenced by more than
      one name by using the  or the alias operator
     The change in the value of the variable by the
      called or the calling program is reflected in all the
      affected functions




©NIIT                                  OOPS/Lesson 7/Slide 18 of 25
Constructors and Destructors

Problem Statement 5.P.2
Predict the Output:
   #include iostream
   void square(int );
   class functionCall
   {
      int number;
      public:
      functionCall();
   };
   functionCall::functionCall()
   {
      number=10;square(number);
   }
©NIIT                          OOPS/Lesson 7/Slide 19 of 25
Constructors and Destructors


Problem Statement 5.P.2 (Contd.)
    void square(int num)
    {
      coutnumendl;
        num *= num; //This Expression Is
        //Resolved As num = num * num
        cout  num  endl;
    }
    int main()
    {
      functionCall f1;
      return 0;
    }
©NIIT                          OOPS/Lesson 7/Slide 20 of 25
Constructors and Destructors

Call by Reference using Pointers
To define and declare a pointer variable:
 Using pointers
     Involves a pointer variable storing the memory
      address of any variable
     Is advantageous since it allows direct access to
      individual bytes in the memory and output devices
    Example:
        char var = 'G';
        char *ptr ; //Pointer Declaration
        ptr = var; //Stores the address of
                    //the variable

©NIIT                                OOPS/Lesson 7/Slide 21 of 25
Constructors and Destructors


Call by Reference using Pointers (Contd.)
 Using pointers
     Allows dynamic allocation and release of memory
      that is program can obtain memory while it is
      running by using new and release by using delete
      operator
    Syntax:
    variable = new type;
        The type of variable mentioned on the left hand and
        the type mentioned on the right side of the new
        operator should match
        delete variable
©NIIT                                 OOPS/Lesson 7/Slide 22 of 25
Constructors and Destructors


Summary
In this lesson, you learned that:
 Constructors are member functions of any class and
  are invoked the moment an instance of the class to
  which they belong is created
 A constructor function has the same name as its class
 A destructor function is invoked when any instance of
  a class ceases to exist
 A destructor function has the same name as its class
  but prefixed with a ~ (tilde)
 The member functions and the constructors of a class
  can also be defined outside the boundary of the class,
  using the scope resolution operator (::)
©NIIT                               OOPS/Lesson 7/Slide 23 of 25
Constructors and Destructors


Summary (Contd.)
 The data that the function must receive when called
  from another function is/are called the parameters of a
  function
 In C++ programs, functions that have parameters are
  invoked in one of the following ways:
    A call by value
    A call by reference
 You can give two names to a variable by using the
  alias operator
 A reference provides an alias, or an alternate name
  for the variable

©NIIT                               OOPS/Lesson 7/Slide 24 of 25
Constructors and Destructors


Summary (Contd.)
 A pointer is a variable that stores the memory address
  of another variable
 Dynamic allocation is the means by which a program
  can obtain memory while it is running
 The capability of obtaining memory as the need arises
  is provided by the new operator
 The delete operator is used to release memory




©NIIT                              OOPS/Lesson 7/Slide 25 of 25

Weitere ähnliche Inhalte

Was ist angesagt?

12 iec t1_s1_oo_ps_session_17
12 iec t1_s1_oo_ps_session_1712 iec t1_s1_oo_ps_session_17
12 iec t1_s1_oo_ps_session_17Niit Care
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notesSrikanth
 
06 iec t1_s1_oo_ps_session_08
06 iec t1_s1_oo_ps_session_0806 iec t1_s1_oo_ps_session_08
06 iec t1_s1_oo_ps_session_08Niit Care
 
Web application architecture
Web application architectureWeb application architecture
Web application architectureIlio Catallo
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesSreedhar Chowdam
 
C Programming Language
C Programming LanguageC Programming Language
C Programming LanguageRTS Tech
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 
Python-oop
Python-oopPython-oop
Python-oopRTS Tech
 
Virtual function
Virtual functionVirtual function
Virtual functionharman kaur
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Naveen Kumar
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsPlatonov Sergey
 

Was ist angesagt? (20)

12 iec t1_s1_oo_ps_session_17
12 iec t1_s1_oo_ps_session_1712 iec t1_s1_oo_ps_session_17
12 iec t1_s1_oo_ps_session_17
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
C++ rajan
C++ rajanC++ rajan
C++ rajan
 
Ocs752 unit 5
Ocs752   unit 5Ocs752   unit 5
Ocs752 unit 5
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
06 iec t1_s1_oo_ps_session_08
06 iec t1_s1_oo_ps_session_0806 iec t1_s1_oo_ps_session_08
06 iec t1_s1_oo_ps_session_08
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Ocs752 unit 4
Ocs752   unit 4Ocs752   unit 4
Ocs752 unit 4
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Python-oop
Python-oopPython-oop
Python-oop
 
Virtual function
Virtual functionVirtual function
Virtual function
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 

Ähnlich wie Aae oop xp_07

Aae oop xp_08
Aae oop xp_08Aae oop xp_08
Aae oop xp_08Niit Care
 
Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsDudy Ali
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#Rainer Stropek
 
Aae oop xp_03
Aae oop xp_03Aae oop xp_03
Aae oop xp_03Niit Care
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1karmuhtam
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptManivannan837728
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptxAnantjain234527
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IAjit Nayak
 
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In  JavaMethod, Constructor, Method Overloading, Method Overriding, Inheritance In  Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In JavaJamsher bhanbhro
 

Ähnlich wie Aae oop xp_07 (20)

Aae oop xp_08
Aae oop xp_08Aae oop xp_08
Aae oop xp_08
 
Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & Destructors
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#
 
Functions
FunctionsFunctions
Functions
 
Aae oop xp_03
Aae oop xp_03Aae oop xp_03
Aae oop xp_03
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In  JavaMethod, Constructor, Method Overloading, Method Overriding, Inheritance In  Java
Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
 

Mehr von Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Kürzlich hochgeladen

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Kürzlich hochgeladen (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Aae oop xp_07

  • 1. Constructors and Destructors Objectives In this lesson, you will learn to: Identify the need for constructors Declare constructors Identify the need for destructors Declare destructors Use scope resolution operator Use constructors with parameters Invoke member functions by using: The call by value method ©NIIT OOPS/Lesson 7/Slide 1 of 25
  • 2. Constructors and Destructors Objectives (Contd.) The call by reference method ® Using alias ® Using pointer ©NIIT OOPS/Lesson 7/Slide 2 of 25
  • 3. Constructors and Destructors Constructors Are used to initialize the member variables of the class when the objects of the class are created Must have the same name as that of class name Cannot return any value, not even a void type Class can have more than one constructors defined in it (known as overloaded constructors) Default constructors accept no parameters and are automatically invoked by the compiler ©NIIT OOPS/Lesson 7/Slide 3 of 25
  • 4. Constructors and Destructors Need for Constructors To initialize a member variable at the time of declaration ©NIIT OOPS/Lesson 7/Slide 4 of 25
  • 5. Constructors and Destructors Declaration of Constructors Example: class Calculator { private: int number1, number2, tot; public: ... Calculator() { number1 = number2 = tot = 0; cout Constructor invoked endl; } }; ©NIIT OOPS/Lesson 7/Slide 5 of 25
  • 6. Constructors and Destructors Destructors Are used to de-initialize the objects when they are destroyed Are used to clear memory space occupied by a data member when an object goes out of scope Must have the same name as that of the class, preceded by a ~ (For example: ~Calculator()) Are automatically invoked Can also be explicitly invoked when required Cannot be overloaded ©NIIT OOPS/Lesson 7/Slide 6 of 25
  • 7. Constructors and Destructors Need for Destructors To de-initialize the objects when they are destroyed To clear memory space occupied by a data member when an object goes out of scope ©NIIT OOPS/Lesson 7/Slide 7 of 25
  • 8. Constructors and Destructors Declaration of Destructors Example: /* This Code Shows The Use Of Destructor In The Calculator Class */ class Calculator { private: int number1, number2, tot; public: ... ~Calculator() //Body Of The //Destructor { number1 = number2 = tot = 0; } }; ©NIIT OOPS/Lesson 7/Slide 8 of 25
  • 9. Constructors and Destructors Just a Minute… Given is a code snippet for the main() function of a program. How would you ensure that the following tasks are accomplished when the program is executed: 1. The member variables are initialized with zero 2. On exit or termination of the program the following message is displayed : “Bye Folks!!! Have a Nice Time” #include iostream int main() { Number num1;num1.disp(); } Hint: The Number class has only one member variable ©NIIT myNum. OOPS/Lesson 7/Slide 9 of 25
  • 10. Constructors and Destructors Scope Resolution Operator (::) Is used to define member functions outside the class definition therefore making the class definition more readable Example: class calculator { public: void input(); }; void calculator::input () {…} ©NIIT OOPS/Lesson 7/Slide 10 of 25
  • 11. Constructors and Destructors Constructors with Parameters Allow member variables of the class to be initialized with user supplied values from main() function also called parameters Example class calculate { private: int num1,num2,total; public: calculate(int, int); }; ©NIIT OOPS/Lesson 7/Slide 11 of 25
  • 12. Constructors and Destructors Constructors with Parameters (Contd.) calculate::calculate(int x, int y) { num1=x;num2=y; total=0; } int main() {//Accept values in two variable var1 //var2 calculate c1(var1,var2); } ©NIIT OOPS/Lesson 7/Slide 12 of 25
  • 13. Constructors and Destructors Invoking Member Functions By using call by value By using call by reference ©NIIT OOPS/Lesson 7/Slide 13 of 25
  • 14. Constructors and Destructors Call by Value Is useful when the function does not need to modify the values of the original variables Does not affect the values of the variables in caller functions ©NIIT OOPS/Lesson 7/Slide 14 of 25
  • 15. Constructors and Destructors Problem Statement 5.P.1 Predict the Output: #include iostream void square(int); class functionCall { int number; public: functionCall(); }; functionCall::functionCall() { number=10;square(number); } ©NIIT OOPS/Lesson 7/Slide 15 of 25
  • 16. Constructors and Destructors Problem Statement 5.P.1 (Contd.) void square(int num) { coutnumendl; num *= num; //This Expression Is //Resolved As num = num * num cout num endl; } int main() { functionCall f1; return 0; } ©NIIT OOPS/Lesson 7/Slide 16 of 25
  • 17. Constructors and Destructors Call by Reference Is implemented by using An alias Pointers ©NIIT OOPS/Lesson 7/Slide 17 of 25
  • 18. Constructors and Destructors Call by Reference (Contd.) Using an alias The same variable can be referenced by more than one name by using the or the alias operator The change in the value of the variable by the called or the calling program is reflected in all the affected functions ©NIIT OOPS/Lesson 7/Slide 18 of 25
  • 19. Constructors and Destructors Problem Statement 5.P.2 Predict the Output: #include iostream void square(int ); class functionCall { int number; public: functionCall(); }; functionCall::functionCall() { number=10;square(number); } ©NIIT OOPS/Lesson 7/Slide 19 of 25
  • 20. Constructors and Destructors Problem Statement 5.P.2 (Contd.) void square(int num) { coutnumendl; num *= num; //This Expression Is //Resolved As num = num * num cout num endl; } int main() { functionCall f1; return 0; } ©NIIT OOPS/Lesson 7/Slide 20 of 25
  • 21. Constructors and Destructors Call by Reference using Pointers To define and declare a pointer variable: Using pointers Involves a pointer variable storing the memory address of any variable Is advantageous since it allows direct access to individual bytes in the memory and output devices Example: char var = 'G'; char *ptr ; //Pointer Declaration ptr = var; //Stores the address of //the variable ©NIIT OOPS/Lesson 7/Slide 21 of 25
  • 22. Constructors and Destructors Call by Reference using Pointers (Contd.) Using pointers Allows dynamic allocation and release of memory that is program can obtain memory while it is running by using new and release by using delete operator Syntax: variable = new type; The type of variable mentioned on the left hand and the type mentioned on the right side of the new operator should match delete variable ©NIIT OOPS/Lesson 7/Slide 22 of 25
  • 23. Constructors and Destructors Summary In this lesson, you learned that: Constructors are member functions of any class and are invoked the moment an instance of the class to which they belong is created A constructor function has the same name as its class A destructor function is invoked when any instance of a class ceases to exist A destructor function has the same name as its class but prefixed with a ~ (tilde) The member functions and the constructors of a class can also be defined outside the boundary of the class, using the scope resolution operator (::) ©NIIT OOPS/Lesson 7/Slide 23 of 25
  • 24. Constructors and Destructors Summary (Contd.) The data that the function must receive when called from another function is/are called the parameters of a function In C++ programs, functions that have parameters are invoked in one of the following ways: A call by value A call by reference You can give two names to a variable by using the alias operator A reference provides an alias, or an alternate name for the variable ©NIIT OOPS/Lesson 7/Slide 24 of 25
  • 25. Constructors and Destructors Summary (Contd.) A pointer is a variable that stores the memory address of another variable Dynamic allocation is the means by which a program can obtain memory while it is running The capability of obtaining memory as the need arises is provided by the new operator The delete operator is used to release memory ©NIIT OOPS/Lesson 7/Slide 25 of 25