SlideShare a Scribd company logo
1 of 11
Download to read offline
Page 1 of 11
                       Constru ctor and Destru ctor

1 What is Constructor?
It is a member function which is automatically used to initialize the objects of the class
type with legal initial values.

2 Why you should define a Constructor ?
Uninitialized member fields have garbage in them. This creates the possibility of a
serious bug (eg, an uninitialized pointer, illegal values, inconsistent values, ...).

3 How can we declaring a constructor.
A constructor is similar to a function, but with the following differences.
        No return type.
        No return statement.

Example:
  class Point {
       public:
         Point(); // parameterless default constructor
         Point(int new_x, int new_y); // constructor with parameters
         int getX();
         int getY();
       private:
         int x;
         int y;
  };



4 Define any five characteristics of Constructor.

        They are called automatically when the objects are created.
        All objects of the class having a constructor are initialize before some use.
        The address of a constructor cannot be taken.
        These cannot be static.
        Return type cannot be specified for constructors.


5 What are the types of Constructor (Write any Four.)?
   Default constructors
   Parameterized Constructor

                             Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 11
      Overloaded Constructor
      Copy Constructor

6 What is Default Constructor?
A default constructor is a constructor that either has no parameters, or if it has
parameters, all the parameters have default values.

7 What is Parameterized Constructor?
A Constructor with arguments is called a parameterized constructor.


8 What is Overloaded Constructor?
Like function Overloading Constructor Overloading can also be done.

9 What is Copy Constructor? Explain with example.
Copy constructor is

      a constructor function with the same name as the class
      used to make deep copy of objects.

For ex:
   class A //Without copy constructor
   {
      private:
      int x;
      public:
      A() {A = 10;}
      ~A() {}
   }

    class B //With copy constructor
    {
       private:
       char *name;
       public:
       B()
       {
       name = new char[20];
       }
       ~B()
       {
       delete name[];
       }
   //Copy constructor
       B(const B &b)
       {
       name = new char[20];
       strcpy(name, b.name);

                            Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 11
        }
   };


Let us Imagine if you don't have a copy constructor for the class B. At the first place, if
an object is created from some existing object, we cannot be sure that the memory is
allocated. Also, if the memory is deleted in destructor, the delete operator might be called
twice for the same memory location.

This is a major risk. One happy thing is, if the class is not so complex this will come to
the fore during development itself. But if the class is very complicated, then these kind of
errors will be difficult to track.

10 Explain any three important places where a copy constructor is called.
    When an object is created from another object of the same type
    When an object is passed by value as a parameter to a function
    When an object is returned from a function


11 What is Dynamic Initialization of objects?
If we initialized class objects at run time, it is the case of Dynamic Initialization.

12 Define Destructors. With Syntax.
Destructors are less complicated than constructors. You don't call them explicitly (they
are called automatically for you), and there's only one destructor for each object. The
name of the destructor is the name of the class, preceeded by a tilde (~). Here's an
example of a destructor:
Player::~Player() {
 strength = 0;
 agility = 0;
 health = 0;
}

13 What are the characteristics of Destructors? Any Five
    These are called automatically when the objects are destroyed.
    Destructor functions follow the usual access rules as other member functions.
    No arguments and return type permitted with destructors.
    These cannot be inherited.
    Address of a destructor cannot be taken.


Answer the questions (i) and (II) after going through the following class:
Class Maths
{
Char chapter[20];
int marks[20];
public:
Maths()                                     // Function 1
                            Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 11
{
Strcpy(chapter, “Cons”);
Marks=90;
cout<<”Chapter Intialised”;
}
~Maths()                              // Function 2
{
cout<<”Chapter Over”;
}
};

   (i)     Name the specific features of class shown by member function 1 and
           member function 2 in above example.
            Function 1: Constructor or Default Constructor
            Function 2: Destructor

   (ii)    How would member function 1 and function 2 get executed?
            When an object of class Maths is created Function 1 is executed.
            Function 2 is invoked automatically when the scope of an object of class
             Maths comes to an end.



INHERITANCE


1 What is Inheritance? Explain.
Inheritance is the process by which new classes called derived classes are created from
existing classes called base classes. The derived classes have all the features of the base
class and the programmer can choose to add new features specific to the newly created
derived class.

For example, a programmer can create a base class named fruit and define derived
classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange,
banana, etc.) has all the features of the base class (fruit) with additional attributes or
features specific to these newly created derived classes. Mango would have its own
defined features, orange would have its own defined features, banana would have its own
defined features, etc.

This concept of Inheritance leads to the concept of polymorphism.

2 What are the features or Advantages of Inheritance:
Reusability:
Inheritance helps the code to be reused in many situations. The base class is defined and
once it is compiled, it need not be reworked. Using the concept of inheritance, the
programmer can create as many derived classes from the base class as needed while
adding specific features to each derived class as needed.
Saves Time and Effort:

                            Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 11
The above concept of reusability achieved by inheritance saves the programmer time and
effort. Since the main code written can be reused in various situations as needed.
Increases Program Structure which results in greater reliability.


3 Write general form for implementing the concept of Inheritance:
class derived_classname: access specifier baseclassname
For example, if the base class is exforsys and the derived class is sample it is specified as:

       class sample: public exforsys
The above makes sample have access to both public and protected variables of base class
exforsys. Reminder about public, private and protected access specifiers:
If a member or variables defined in a class is private, then they are accessible by
members of the same class only and cannot be accessed from outside the class.
.
Public members and variables are accessible from outside the class.
.
Protected access specifier is a stage between private and public. If a member functions or
variables defined in a class are protected, then they cannot be accessed from outside the
class but can be accessed from the derived class.


4 What are the types of Inheritance? Explain Each.
Single inheritance
When a derived class inherits only from one base class, it is known as single inheritance.

               X                       Base Class




               Y                       Derived Class




Multiple inheritance
When the derived class inherits from multiple base classes, it is known as Multiple
inheritance.




                            Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 11


             X                                Y                       Base classes




                               Z
                                                                        Derived class

Multilevel inheritance
When a derived class inherits from a class that itself inherits from another class, it known
as multilevel inheritance.
                                   X                               Base class of Y




                                   Y                                 Sub class of X
                                                                     Base class of Z


                                   Z                                 Derived class of Y




Hierarchical inheritance
When the properties of one class may be inherited by more than one class, it is known as
Hierarchical inheritance

                           Z                                  Base class


         X                                Y
                                                             Derived classes




Hybrid inheritance
When a derived class inherits from multiple base classes and all of its base classes
inherits from a single base class, this form of inheritance is known as hybrid inheritance.




                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 7 of 11

                       W                                    Base classes



                                                          X and Y are sub class
         X                             Y                         of W



                         Z
                                                               Derived class



5 Differentiate between private and protected members.
The Protected and private members are hidden from outside world of a class ie both
cannot be accessed by non member and non friend functions. However, the difference is
that private members are not inherited by derived class whereas protected members are
inherited by the derived class.

Write the output of given example of Inheritance Example:
class exforsys
{public:
exforsys(void) { x=0; }
void f(int n1)
{x= n1*5;
}
void output(void) { cout<<x; }
private:
int x; };
class sample: public exforsys
{ public:
sample(void) { s1=0; }
void f1(int n1)
{s1=n1*10;}
void output(void)
{exforsys::output();
cout << s1; }
private:
int s1;};
int main(void)
{ sample s;
s.f(10);
s.output();
s.f1(20);
s.output();
}

                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 8 of 11
The output of the above program is
50
200

Explanation
In the above example, the derived class is sample and the base class is exforsys. The
derived class defined above has access to all public and private variables. Derived classes
cannot have access to base class constructors and destructors. The derived class would be
able to add new member functions, or variables, or new constructors or new destructors.
In the above example, the derived class sample has new member function f1( ) added in
it. The line:

       sample s;
creates a derived class object named as s. When this is created, space is allocated for the
data members inherited from the base class exforsys and space is additionally allocated
for the data members defined in the derived class sample.
The base class constructor exforsys is used to initialize the base class data members and
the derived class constructor sample is used to initialize the data members defined in
derived class.


6 What is Visibility Mode? Write their types too.
These control the access specifier to be inheritable members of the base class, in he
derived class.

The types of Visibility modes are
    The Public
    The Protected
    The Private


7 Explain the role of each Visibility Mode?
    The Public
      In this mode, the derived class can access the public and protected members of the
      base class publically.

      The Protected
       In this mode, the derived class can access the public and protected members of the
       base class protectedly

      The Private
       In this mode, the derived class can access the public and protected members of the
       base class privately.




                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 9 of 11



8 Explain Virtual Base Class.
Virtual Base Classes

                          In the above example, there are two derived classes Exf1 and
Exf2 from the base class Exforsys. As shown in the above diagram, the Training class is
derived from both of the derived classes Exf1 and Exf2. In this scenario, if a user has a
member function in the class Training where the user wants to access the data or member
functions of the class Exforsys it would result in error if it is performed like this:


class Exforsys
{
protected:
int x;
};

class Exf1:public Exforsys
{ };

class Exf2:public Exforsys
{ };

class Training:public Exf1,public Exf2
{
public:
int example()
{
return x;
}
};

The above program results in a compile time error as the member function example() of
class Training tries to access member data x of class Exforsys. This results in an error
because the derived classes Exf1 and Exf2 (derived from base class Exforsys) create
copies of Exforsys called subobjects.

This means that each of the subobjects have Exforsys member data and member
functions and each have one copy of member data x. When the member function of the
class Training tries to access member data x, confusion arises as to which of the two
copies it must access since it derived from both derived classes, resulting in a compile
time error.

When this occurs, Virtual base class is used. Both of the derived classes Exf1 and Exf2
are created as virtual base classes, meaning they should share a common subobject in
their base class.

                             Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 10 of 11
For Example:


class Exforsys
{ protected:
int x;
;
class Exf1:virtual public Exforsys
{ };
class Exf2:virtual public Exforsys
{ };
class Training:public Exf1,public Exf2
{
public:
int example()
{ return x; } };

Because a class can be an indirect base class to a derived class more than once, C++
provides a way to optimize the way such base classes work. Virtual base classes offer a
way to save space and avoid ambiguities in class hierarchies that use multiple inheritance.

14 Consider the following declarations and answer the questions given below:

class LB
{ char name[20];
protected:
int jaws;
public:
void inputdata(char, int);
void outputdata();
};
class animal:protected LB
{
int tail;
protected:
int legs;
public:
void readdata(int,int);
void writedata();
};
class cow:private animal
{
int horn_size;
public:
void fetchdata(int);
void displaydata();
};


                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 11 of 11
(i)     Name the base class and derived class of class animal.
(ii)    Name the data member that can be accessed from function displaydata().
(iii)   Name the data members that can be accessed by an object of cow class.
(iv)    Is the member function outputdata() accessible to the object of animal class.

Ans i Base class of animal is LB, Derived class of animal is cow.
Ans ii The data members which can be accessed from function displaydata() are
        horn_size, legs and jaws.
Ans iii The object of cow class cannot be directly access any data member.
Ans iv No




                       Prepared By Sumit Kumar Gupta, PGT Computer Science

More Related Content

What's hot

constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorSunipa Bera
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++aleenaguen
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java pptkunal kishore
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++Learn By Watch
 
[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 TypesMuhammad Hammad Waseem
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2Abbas Ajmal
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructorVENNILAV6
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Java Constructors | Java Course
Java Constructors | Java CourseJava Constructors | Java Course
Java Constructors | Java CourseRAKESH P
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.pptKarthik Sekar
 

What's hot (20)

constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
 
[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
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors
ConstructorsConstructors
Constructors
 
Java Constructors | Java Course
Java Constructors | Java CourseJava Constructors | Java Course
Java Constructors | Java Course
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Inheritance
InheritanceInheritance
Inheritance
 

Viewers also liked (20)

Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes
 
Pointers
PointersPointers
Pointers
 
Unit 3
Unit  3Unit  3
Unit 3
 
File handling
File handlingFile handling
File handling
 
2-D array
2-D array2-D array
2-D array
 
1-D array
1-D array1-D array
1-D array
 
Functions
FunctionsFunctions
Functions
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
Stack
StackStack
Stack
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocation
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Ashish oot
Ashish ootAshish oot
Ashish oot
 
c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
 
Queue
QueueQueue
Queue
 
Inheritance
InheritanceInheritance
Inheritance
 

Similar to Constructor & destructor

Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSwarup Boro
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Shweta Shah
 
PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxAtikur Rahman
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple InheritanceBhavyaJain137
 
Inheritance,constructor,friend function
Inheritance,constructor,friend functionInheritance,constructor,friend function
Inheritance,constructor,friend functionFAKRUL ISLAM
 
14_inheritance.ppt
14_inheritance.ppt14_inheritance.ppt
14_inheritance.pptsundas65
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdfstudy material
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesCtOlaf
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdfWaqarRaj1
 
Polymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPolymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPriyanshuMittal31
 
Oop04 6
Oop04 6Oop04 6
Oop04 6schwaa
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfismartshanker1
 

Similar to Constructor & destructor (20)

Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Inheritance
InheritanceInheritance
Inheritance
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance
Inheritance Inheritance
Inheritance
 
PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptx
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
Inheritance,constructor,friend function
Inheritance,constructor,friend functionInheritance,constructor,friend function
Inheritance,constructor,friend function
 
14_inheritance.ppt
14_inheritance.ppt14_inheritance.ppt
14_inheritance.ppt
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
Polymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPolymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformatics
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop04 6
Oop04 6Oop04 6
Oop04 6
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
 

More from Swarup Kumar Boro

More from Swarup Kumar Boro (14)

c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Boolean algebra laws
Boolean algebra lawsBoolean algebra laws
Boolean algebra laws
 
Class
ClassClass
Class
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Physics
PhysicsPhysics
Physics
 
Physics activity
Physics activityPhysics activity
Physics activity
 

Recently uploaded

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Constructor & destructor

  • 1. Page 1 of 11 Constru ctor and Destru ctor 1 What is Constructor? It is a member function which is automatically used to initialize the objects of the class type with legal initial values. 2 Why you should define a Constructor ? Uninitialized member fields have garbage in them. This creates the possibility of a serious bug (eg, an uninitialized pointer, illegal values, inconsistent values, ...). 3 How can we declaring a constructor. A constructor is similar to a function, but with the following differences.  No return type.  No return statement. Example: class Point { public: Point(); // parameterless default constructor Point(int new_x, int new_y); // constructor with parameters int getX(); int getY(); private: int x; int y; }; 4 Define any five characteristics of Constructor.  They are called automatically when the objects are created.  All objects of the class having a constructor are initialize before some use.  The address of a constructor cannot be taken.  These cannot be static.  Return type cannot be specified for constructors. 5 What are the types of Constructor (Write any Four.)?  Default constructors  Parameterized Constructor Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 11  Overloaded Constructor  Copy Constructor 6 What is Default Constructor? A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. 7 What is Parameterized Constructor? A Constructor with arguments is called a parameterized constructor. 8 What is Overloaded Constructor? Like function Overloading Constructor Overloading can also be done. 9 What is Copy Constructor? Explain with example. Copy constructor is  a constructor function with the same name as the class  used to make deep copy of objects. For ex: class A //Without copy constructor { private: int x; public: A() {A = 10;} ~A() {} } class B //With copy constructor { private: char *name; public: B() { name = new char[20]; } ~B() { delete name[]; } //Copy constructor B(const B &b) { name = new char[20]; strcpy(name, b.name); Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 11 } }; Let us Imagine if you don't have a copy constructor for the class B. At the first place, if an object is created from some existing object, we cannot be sure that the memory is allocated. Also, if the memory is deleted in destructor, the delete operator might be called twice for the same memory location. This is a major risk. One happy thing is, if the class is not so complex this will come to the fore during development itself. But if the class is very complicated, then these kind of errors will be difficult to track. 10 Explain any three important places where a copy constructor is called.  When an object is created from another object of the same type  When an object is passed by value as a parameter to a function  When an object is returned from a function 11 What is Dynamic Initialization of objects? If we initialized class objects at run time, it is the case of Dynamic Initialization. 12 Define Destructors. With Syntax. Destructors are less complicated than constructors. You don't call them explicitly (they are called automatically for you), and there's only one destructor for each object. The name of the destructor is the name of the class, preceeded by a tilde (~). Here's an example of a destructor: Player::~Player() { strength = 0; agility = 0; health = 0; } 13 What are the characteristics of Destructors? Any Five  These are called automatically when the objects are destroyed.  Destructor functions follow the usual access rules as other member functions.  No arguments and return type permitted with destructors.  These cannot be inherited.  Address of a destructor cannot be taken. Answer the questions (i) and (II) after going through the following class: Class Maths { Char chapter[20]; int marks[20]; public: Maths() // Function 1 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 11 { Strcpy(chapter, “Cons”); Marks=90; cout<<”Chapter Intialised”; } ~Maths() // Function 2 { cout<<”Chapter Over”; } }; (i) Name the specific features of class shown by member function 1 and member function 2 in above example.  Function 1: Constructor or Default Constructor  Function 2: Destructor (ii) How would member function 1 and function 2 get executed?  When an object of class Maths is created Function 1 is executed.  Function 2 is invoked automatically when the scope of an object of class Maths comes to an end. INHERITANCE 1 What is Inheritance? Explain. Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc. This concept of Inheritance leads to the concept of polymorphism. 2 What are the features or Advantages of Inheritance: Reusability: Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. Saves Time and Effort: Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 11 The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed. Increases Program Structure which results in greater reliability. 3 Write general form for implementing the concept of Inheritance: class derived_classname: access specifier baseclassname For example, if the base class is exforsys and the derived class is sample it is specified as: class sample: public exforsys The above makes sample have access to both public and protected variables of base class exforsys. Reminder about public, private and protected access specifiers: If a member or variables defined in a class is private, then they are accessible by members of the same class only and cannot be accessed from outside the class. . Public members and variables are accessible from outside the class. . Protected access specifier is a stage between private and public. If a member functions or variables defined in a class are protected, then they cannot be accessed from outside the class but can be accessed from the derived class. 4 What are the types of Inheritance? Explain Each. Single inheritance When a derived class inherits only from one base class, it is known as single inheritance. X Base Class Y Derived Class Multiple inheritance When the derived class inherits from multiple base classes, it is known as Multiple inheritance. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 11 X Y Base classes Z Derived class Multilevel inheritance When a derived class inherits from a class that itself inherits from another class, it known as multilevel inheritance. X Base class of Y Y Sub class of X Base class of Z Z Derived class of Y Hierarchical inheritance When the properties of one class may be inherited by more than one class, it is known as Hierarchical inheritance Z Base class X Y Derived classes Hybrid inheritance When a derived class inherits from multiple base classes and all of its base classes inherits from a single base class, this form of inheritance is known as hybrid inheritance. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 7. Page 7 of 11 W Base classes X and Y are sub class X Y of W Z Derived class 5 Differentiate between private and protected members. The Protected and private members are hidden from outside world of a class ie both cannot be accessed by non member and non friend functions. However, the difference is that private members are not inherited by derived class whereas protected members are inherited by the derived class. Write the output of given example of Inheritance Example: class exforsys {public: exforsys(void) { x=0; } void f(int n1) {x= n1*5; } void output(void) { cout<<x; } private: int x; }; class sample: public exforsys { public: sample(void) { s1=0; } void f1(int n1) {s1=n1*10;} void output(void) {exforsys::output(); cout << s1; } private: int s1;}; int main(void) { sample s; s.f(10); s.output(); s.f1(20); s.output(); } Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 8. Page 8 of 11 The output of the above program is 50 200 Explanation In the above example, the derived class is sample and the base class is exforsys. The derived class defined above has access to all public and private variables. Derived classes cannot have access to base class constructors and destructors. The derived class would be able to add new member functions, or variables, or new constructors or new destructors. In the above example, the derived class sample has new member function f1( ) added in it. The line: sample s; creates a derived class object named as s. When this is created, space is allocated for the data members inherited from the base class exforsys and space is additionally allocated for the data members defined in the derived class sample. The base class constructor exforsys is used to initialize the base class data members and the derived class constructor sample is used to initialize the data members defined in derived class. 6 What is Visibility Mode? Write their types too. These control the access specifier to be inheritable members of the base class, in he derived class. The types of Visibility modes are  The Public  The Protected  The Private 7 Explain the role of each Visibility Mode?  The Public In this mode, the derived class can access the public and protected members of the base class publically.  The Protected In this mode, the derived class can access the public and protected members of the base class protectedly  The Private In this mode, the derived class can access the public and protected members of the base class privately. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 9. Page 9 of 11 8 Explain Virtual Base Class. Virtual Base Classes In the above example, there are two derived classes Exf1 and Exf2 from the base class Exforsys. As shown in the above diagram, the Training class is derived from both of the derived classes Exf1 and Exf2. In this scenario, if a user has a member function in the class Training where the user wants to access the data or member functions of the class Exforsys it would result in error if it is performed like this: class Exforsys { protected: int x; }; class Exf1:public Exforsys { }; class Exf2:public Exforsys { }; class Training:public Exf1,public Exf2 { public: int example() { return x; } }; The above program results in a compile time error as the member function example() of class Training tries to access member data x of class Exforsys. This results in an error because the derived classes Exf1 and Exf2 (derived from base class Exforsys) create copies of Exforsys called subobjects. This means that each of the subobjects have Exforsys member data and member functions and each have one copy of member data x. When the member function of the class Training tries to access member data x, confusion arises as to which of the two copies it must access since it derived from both derived classes, resulting in a compile time error. When this occurs, Virtual base class is used. Both of the derived classes Exf1 and Exf2 are created as virtual base classes, meaning they should share a common subobject in their base class. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 10. Page 10 of 11 For Example: class Exforsys { protected: int x; ; class Exf1:virtual public Exforsys { }; class Exf2:virtual public Exforsys { }; class Training:public Exf1,public Exf2 { public: int example() { return x; } }; Because a class can be an indirect base class to a derived class more than once, C++ provides a way to optimize the way such base classes work. Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritance. 14 Consider the following declarations and answer the questions given below: class LB { char name[20]; protected: int jaws; public: void inputdata(char, int); void outputdata(); }; class animal:protected LB { int tail; protected: int legs; public: void readdata(int,int); void writedata(); }; class cow:private animal { int horn_size; public: void fetchdata(int); void displaydata(); }; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 11. Page 11 of 11 (i) Name the base class and derived class of class animal. (ii) Name the data member that can be accessed from function displaydata(). (iii) Name the data members that can be accessed by an object of cow class. (iv) Is the member function outputdata() accessible to the object of animal class. Ans i Base class of animal is LB, Derived class of animal is cow. Ans ii The data members which can be accessed from function displaydata() are horn_size, legs and jaws. Ans iii The object of cow class cannot be directly access any data member. Ans iv No Prepared By Sumit Kumar Gupta, PGT Computer Science