Constructors and Destructor_detilaed contents.pptx
vijayaazeem
2 views
61 slides
Mar 05, 2025
Slide 1 of 61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
About This Presentation
Constructors and Destructors.pptx -full
Size: 556.12 KB
Language: en
Added: Mar 05, 2025
Slides: 61 pages
Slide Content
Constructors and Destructors
Example of Class and Object in C++ // C++ program to illustrate how create a simple class and object #include < iostream > #include <string> using namespace std ; // Define a class named 'Person' class Person { public: // Data members string name; int age; // Member function to introduce the person void introduce() { cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl ; } };
int main() { // Create an object of the Person class Person person1; // accessing data members person1.name = "Alice"; person1.age = 30; // Call the introduce member method person1.introduce(); return 0; }
Access Modifiers In C++ classes, we can control the access to the members of the class using Access Specifiers . Also known as access modifier , they are the keywords that are specified in the class and all the members of the class under that access specifier will have particular access level. In C++, there are 3 access specifiers that are as follows: Public: Members declared as public can be accessed from outside the class. Private: Members declared as private can only be accessed within the class itself. Protected: Members declared as protected can be accessed within the class and by derived classes.
Example of access modifiers // C++ program to demonstrate accessing of data members #include < iostream > using namespace std ; class Fruit { private: string fruitname ; // Access specifier public: // Member Functions() void setfruitName (string name) { fruitname = name; } void printfruit name() { cout << “ Fruitname is:" << Fruitname ; } };
int main() { // Declare an object of class geeks Fruit F1; // accessing data member // cannot do it like: obj1.fruitname = “ Bananna "; F1 .setName(“ Bananna "); // accessing member function F1.printname(); return 0; }
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created . It is used to i nitialize the data members of new objects generally . The constructor in C++ has the same name as the class or structure . It constructs the values i.e. provides data for the object which is why it is known as a constructor .
Member Function in C++ Classes There are 2 ways to define a member function: Inside class definition Outside class definition
Till now, we have defined the member function inside the class , but we can also define the member function outside the class. To define a member function outside the class definition, We have to first declare the function prototype in the class definition. Then we have to use the scope resolution:: operator along with the class name and function name.
// C++ program to demonstrate member function definition //outside class #include < iostream.h > using namespace std ; class Fruit { public: string Fruitname ; int id; // printname is not defined inside class definition void printFruitname (); // printid is defined inside class definition void printid () { cout << “ Fruitid is: " << id; } };
// Definition of printname using scope resolution operator :: void Fruit:: printFruitname () { cout << “ Fruitname is: " << Fruitname ; } int main() { Fruit F1; F1 .Fruitname = “Apple"; F11.id = 15; // call printname () F1.printname(); cout << endl ; // call printid () F1.printid(); return 0; }
Syntax of Constructors in C++ The prototype of the constructor looks like this: <class-name> () { ... }
Characteristics of Constructors in C++ The name of the constructor is the same as its class name. Constructors are mostly declared in the public section of the class though they can be declared in the private section of the class. Constructors do not return values ; hence they do not have a return type. A constructor gets called automatically when we create the object of the class .
Default constructor Characteristics of a Default Constructor ✅ Takes no parameters (or all parameters have default values). ✅ Automatically invoked when an object is created. ✅ If no constructor is defined, C++ provides an implicit default constructor . ✅ Used to initialize objects with default values .
#include < iostream > using namespace std ; class Person { string name; int age; public: // Default Constructor Person() { name = "Unknown"; age = 0; cout << "Default Constructor Called" << endl ; } void display() { cout << "Name: " << name << ", Age: " << age << endl ; } }; int main() { Person p1; // Default constructor is called automatically p1.display(); // Output: Name: Unknown, Age: 0 return 0; }
Constructors Constructors are special class members which are called by the compiler every time an object of that class is instantiated . Constructors have the same name as the class and may be defined inside or outside the class definition. There are 4 types of constructors in C++ classes: Default Constructors : The constructor that takes no argument is called default constructor. Parameterized Constructors: This type of constructor takes the arguments to initialize the data members. Copy Constructors : Copy constructor creates the object from an already existing object by copying it. Move Constructor: The move constructor also creates the object from an already existing object but by moving it .
// C++ program to demonstrate constructors #include <bits/ stdc ++.h> using namespace std ; class Fruit { public: int id ; //Default Constructor Fruit() { cout << "Default Constructor called" << endl ; id=-1; } //Parameterized Constructor Fruit( int x) { cout <<"Parameterized Constructor called "<< endl ; id=x; } };
int main() { // obj1 will call Default Constructor Fruit F1,F2(21); cout <<"Fruit F1 id is:" << F1.id << endl ; // obj2 will call Parameterized Constructor cout <<"Fruit F2 id is:" <<F2.id << endl ; return 0; }
Constructor Definitions in C++ In C++, there are 2 methods by which a constructor can be declared: 1Defining the Constructor Within the Class <class-name> (list-of-parameters) { // constructor definition }
2. Defining the Constructor Outside the Class
Example: // Example to show defining the constructor within the class #include < iostream > using namespace std ; // Class definition class student { int rno ; char name[50]; double fee; public: /* Here we will define a constructor inside the same class for which we are creating it. */
student() { // Constructor within the class cout << "Enter the RollNo :"; cin >> rno ; cout << "Enter the Name:"; cin >> name; cout << "Enter the Fee:"; cin >> fee; } // Function to display the data // defined via constructor void display() { cout << endl << rno << "\t" << name << "\t" << fee; } };
int main() { student s; /*constructor gets called automatically as soon as the object of the class is declared */ s.display (); return 0; }
// defining the constructor and function display outside the class #include < iostream > using namespace std ; class student { int rno ; char name[50]; double fee; public: /* To define a constructor outside the class, we need to declare it within the class first. Then we can define the implementation anywhere. */ student(); void display(); }; /* Here we will define a constructor outside the class for whichwe are creating it.*/
// driver code int main() { student s; /* constructor gets called automatically as soon as the object of the class is declared */ s.display (); return 0; }
Copy Constructor in C++ A copy constructor is a member function that initializes an object using another object of the same class . Syntax of Copy Constructor Copy constructor takes a reference to an object of the same class as an argument.
It is also called member-wise initialization because the copy constructor initializes one object with the existing object , both belonging to the same class on a member-by-member copy basis . C++ compiler by default create a simple copy constructor when it is not explicitly defined by the programmer. It is called implicit copy constructor, and it will copy the bases and members of an object in the same order that they were present in the code .( It is automatically generated when an object is copied using another object.)
#include < iostream > using namespace std ; // Create a demo class class A { public: int x; }; int main() { // Creating an a1 object A a1; a1.x = 10; cout << "a1's x = " << a1.x << endl ;
// Creating another object using a Copy Constructor //Calling It is automatically generated when an object is copied using another object. A a2(a1); cout << "a2's x = " << a2.x; return 0; } we were able to construct a2 object using already created object a1 .
When Should We Use the Implicit Copy Constructor? The implicit copy constructor (default constructor provided by the compiler) is safe to use when: Your Class Does Not Have Dynamically Allocated Memory If your class only contains simple data members (like int , float, char, or even std ::string), the implicit copy constructor is sufficient.
If no constructor is defined, C++ provides a default constructor automatically . Default constructors are useful for initializing objects with default values . Can be combined with parameterized constructors using function overloading .
#include < iostream > using namespace std ; class Car { public: string model; int year; }; int main() { Car car1 = {"Toyota", 2022}; // Original object Car car2 = car1; // Compiler provides an implicit copy //constructor cout << car2.model << " - " << car2.year << endl ; // Output: Toyota - 2022 return 0; }
C++ also allows programmers to create their own version of copy constructor known as user defined or explicit copy constructor . Syntax of User Defined Copy Constructor Copy constructor takes a reference to an object of the same class as an argument :
User Defined Copy Constructor Example of Copy Constructor The below example demonstrates how to create and use the copy constructor in C++:
#include < iostream > using namespace std ; // Create a demo class class A { public: int x; A(){}; //default constructor no code but implicit // user defined Copy Constructor definition A (A & t) { x = t.x ; cout << "Calling copy constructor" << endl ; } };
int main() { // Creating an a1 object A a1; a1.x = 10; cout << "a1's x = " << a1.x << endl ; // Creating another object using a1 // Copy Constructor Calling A a2(a1); // or A a2=a1; assign one object to another cout << "a2's x = " << a2.x; return 0; }
#include < iostream > using namespace std ; class Person { string name; int age; public: // Parameterized Constructor Person(string n, int a) { name = n; age = a; } // User-defined Copy Constructor Person( const Person &p) { name = p.name; // Copying data (p cannot be modified) age = p.age ; cout << "Copy Constructor Called" << endl ; } // Why const Person &p in Copy Constructor? The const ensures that p cannot be modified inside //the constructor. Example: Trying p.age = 40; inside the constructor would result in an error. void display() { cout << "Name: " << name << ", Age: " << age << endl ; } };
int main() { Person p1("John", 25); Person p2 = p1; // Copy constructor is called p1.display(); p2.display(); return 0; }
Constant Variables : There are certain set of rules for the declaration and initialization of the constant variables: The const variable cannot be left un-initialized at the time of the declaration. It cannot be assigned value anywhere in the program. Explicit value needed to be provided to the constant variable at the time of declaration of the constant variable.
Pointers can be declared with a const keyword. S o , there are three possible ways to use a const keyword with a pointer, which are as follows: When the pointer variable point to a const value :
// C++ program to demonstrate the // above concept #include < iostream > using namespace std ; // Driver Code int main() { int x{ 10 }; char y{ 'M' }; const int * i = &x; const char* j = &y; // Value of x and y can be altered, // they are not constant variables x = 9; y = 'A'; // Change of constant values because, // i and j are pointing to const-int // & const -char type value // *i = 6; // *j = 7; cout << *i << " " << *j; }
For more infor refer Const keyword in C++ - GeeksforGeeks
Program 1. A program to print student details using constructor and destructor char name[20],add[20]; int roll,zip ; 2. A program to calculate factorial of a given number using copy constructor Enter the Number: 5 Factorial is: 120 Factorial is: 120 3. Program for Add two time variables using constructor and destructor int minutes,hours,a ;
t his pointer #include < iostream > using namespace std ; class Time { int minutes,hours,a ; static int i; public: Time( int a) { this->a=hours=a; this->a+=5; minutes=i++; cout <<"\n Obj address : "<< this; cout < <"\ nAddress of i : "<<&i; cout <<"\n a= "<<this->a<<"\t\t"<< aa Getch (); }; int Time ::i; void main() { Time t3(10),t2(1); }
Static Variables in a Function Static Member Variable in a Class Static Member Functions in a Class Global Static Variable
Static Variables in a Function In a function, when a variable is declared as static, space for it gets allocated for the lifetime of the program . Even if the function is called multiple times, space for the static variable is allocated only once and the value of the variable in the previous call gets carried through the next function call.
#include <bits/ stdc ++.h> using namespace std ; void f() { // Static variable static int count = 0; // The value will be updated and carried over to the next function call count++; cout << count << " "; } int main() { // Calling function f() 5 times for ( int i = 0; i < 5; i++) f(); return 0; }
Static Data Member in a Class As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static member variables in a class are shared by the objects. There cannot be multiple copies of the same static variables for different objects . Also because of this reason static variables cannot be initialized using constructors.
#include < iostream > using namespace std ; class GfG { public: // Static data member declaration static int i; static int j; }; // Definition of static data member int GfG ::i = 0; // Initialize it int GfG ::j = 1; int main() { GfG obj1; GfG obj2; obj1.i = 2; obj2.i = 3; // Prints value of i cout << obj1.i << " " << obj2.i<< obj1.j << " " << obj2.j ; }
Static Member Functions in a Class Just like the static data members or static variables inside the class, static member functions also do not depend on the object of the class. We are allowed to invoke a static member function using the object and the ‘.’ operator but it is recommended to invoke the static members using the class name and the scope resolution operator . Static member functions are allowed to access only the static data members or other static member functions , they cannot access the non-static data members or member functions of the class.
#include < iostream > using namespace std ; class GfG { public: // Static member function static void printMsg () { cout << "Welcome to GfG !"; } }; int main() { // Invoking a static member function GfG :: printMsg (); }
#include < iostream > using namespace std ; class Counter { private: static int count; // Static data member public: // Static function to increment and display count static void increment() { count++; // Modifies the static variable cout << "Count: " << count << endl ; } }; // Definition and initialization of static data member int Counter::count = 0; int main() { // Calling static function using class name (recommended way) Counter::increment(); // Output: Count: 1 Counter::increment(); // Output: Count: 2 // Calling static function using objects (not recommended, but works) Counter obj1, obj2; obj1.increment(); // Output: Count: 3 obj2.increment(); // Output: Count: 4 return 0; }
Global Static Variable in C++ A global static variable is a static variable declared outside all functions, usually at the top of the file. It has file scope, meaning it is only accessible within the file in which it is declared.
#include < iostream > using namespace std ; // Global static variable (restricted to this file) static int counter = 0; class Counter { public: // Function to increment and display global static variable void increment() { counter++; cout << "Counter: " << counter << endl ; } }; int main() { Counter obj1, obj2; obj1.increment(); // Output: Counter: 1 obj2.increment(); // Output: Counter: 2 obj1.increment(); // Output: Counter: 3 return 0; }
#include < iostream > using namespace std ; // Global static variable (restricted to this file) static int counter = 0; class ClassA { public: void increment() { counter++; cout << " ClassA Incremented Counter: " << counter << endl ; } }; class ClassB { public: void increment() { counter++; cout << " ClassB Incremented Counter: " << counter << endl ; } };