SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
Niit Care
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
Farag Zakaria
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
Srikanth
 
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
Niit Care
 

La actualidad más candente (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
 

Similar a Aae oop xp_07

Aae oop xp_08
Aae oop xp_08Aae oop xp_08
Aae oop xp_08
Niit Care
 
Aae oop xp_03
Aae oop xp_03Aae oop xp_03
Aae oop xp_03
Niit Care
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
Niit Care
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 

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

Más de 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
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

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