130 likes | 152 Views
This presentation on Constructors and Destructors in C will cover what are constructor in C and how a constructor is different from the function. You will also learn about the types of constructors and understand destructors in C . You will get an idea about constructor overloading. Finally, we will also do some hands-on examples in this C tutorial for beginners slides.<br>
E N D
What’s in it for you ? What is a constructor in C++ ? Declaration of constructor How constructor is different from the function? Types of constructor Default constructor Parameterized constructor Copy constructor Constructor overloading Destructor in C++
What is a constructor in C++? Constructors are special functions of a class that is used to initialize objects of a class. They are invoked automatically whenever an object is created.
V Declaration of constructor {…} Constructors are the member function of a class, and it has the same name as that of the class. It can be defined inside the class and outside the class as well using the scope resolution operator :: Syntax: Class Cons { Public: int n; Cons() { } };
How constructor is different from the function? • There are some differences between Constructor and function: • Constructor doesn’t have a return type, unlike function. • The name of constructor must be of the same name as that of the class. • Whenever an object is created then a constructor is invoked. • Function can be virtual function but it is not so incase of constructor.
Types of constructors • Types of constructor • Default constructor • Parameterized constructor • Copy constructor
Default constructor A default constructor is a constructor that doesn’t have any arguments inside it. It can either be declared explicitly or can be generated automatically. For a class named Cons, the default constructor would be: Cons() { }
Parameterized constructor A parameterized constructor is similar to that of the default constructor; the only difference is we can pass arguments to the parameterized constructor For a class named Cons, the parameterized constructor would be: Cons(int n1, int n2) { }
Copy constructor A copy constructor is a type of constructor which initializes an object using another object of the class. In this constructor properties of one object is copied to another object. For a class named Cons, the copy constructor would be: Cons (const Cons &obj) { }
y Constructor overloading Like functions, constructors can also be overloaded. The overloaded constructor varies in the number of arguments, which helps determine which constructor should be called. Cons( int x, int y ) { // operations } Cons( int x, int y, int z ) { // operations }
y Destructor in C++ A destructor is also a special function which deletes or destructs the object as soon as the object goes out of scope. Its name is the same as that of the class name with a tilde sign (~). Syntax: ~Cons() { }