C++ Default Constructor

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

C++ Constructor

In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data
members of new object generally. The constructor in C++ has the same name as class or structure.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

Let's see the simple example of C++ default Constructor.

12.7K
Eve Cam: Protect Your Home AND Your PRIVACY! Best Smart Home Camera?!

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

C++ Copy Constructor


A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.
Copy Constructor is of two types:
o Default Copy constructor: The compiler defines the default copy constructor. If the user defines no copy constructor,
compiler supplies its constructor.
o User Defined constructor: The programmer defines the user-defined constructor.

Syntax Of User-defined Copy Constructor:


1. Class_name(const class_name &old_object);

Consider the following situation:

1. class A
2. {
3. A(A &x) // copy constructor.
4. {
5. // copyconstructor.
6. }
7. }

In the above case, copy constructor can be called in the following ways:

Let's see a simple example of the copy constructor.

// program of the copy constructor.

#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}

Output:

20

When Copy Constructor is called


Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the same class type. For example, Student s1 = s2, where
Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.

Two types of copies are produced by the constructor:


o Shallow copy
o Deep copy

Shallow Copy
o The default copy constructor can only produce the shallow copy.
o A Shallow copy is defined as the process of creating the copy of an object by copying data of all the member variables as it
is.

Let's understand this through a simple example:

1. #include <iostream>
2.
3. using namespace std;
4.
5. class Demo
6. {
7. int a;
8. int b;
9. int *p;
10. public:
11. Demo()
12. {
13. p=new int;
14. }
15. void setdata(int x,int y,int z)
16. {
17. a=x;
18. b=y;
19. *p=z;
20. }
21. void showdata()
22. {
23. std::cout << "value of a is : " <<a<< std::endl;
24. std::cout << "value of b is : " <<b<< std::endl;
25. std::cout << "value of *p is : " <<*p<< std::endl;
26. }
27. };
28. int main()
29. {
30. Demo d1;
31. d1.setdata(4,5,7);
32. Demo d2 = d1;
33. d2.showdata();
34. return 0;
35. }

Output:
value of a is : 4
value of b is : 5
value of *p is : 7

In the above case, a programmer has not defined any constructor, therefore, the statement Demo d2 = d1; calls the default
constructor defined by the compiler. The default constructor creates the exact copy or shallow copy of the existing object. Thus, the
pointer p of both the objects point to the same memory location. Therefore, when the memory of a field is freed, the memory of
another field is also automatically freed as both the fields point to the same memory location. This problem is solved by the user-
defined constructor that creates the Deep copy.

Deep copy
Deep copy dynamically allocates the memory for the copy and then copies the actual value, both the source and copy have distinct
memory locations. In this way, both the source and copy are distinct and will not share the same memory location. Deep copy
requires us to write the user-defined constructor.

Let's understand this through a simple example.

1. #include <iostream>
2. using namespace std;
3. class Demo
4. {
5. public:
6. int a;
7. int b;
8. int *p;
9.
10. Demo()
11. {
12. p=new int;
13. }
14. Demo(Demo &d)
15. {
16. a = d.a;
17. b = d.b;
18. p = new int;
19. *p = *(d.p);
20. }
21. void setdata(int x,int y,int z)
22. {
23. a=x;
24. b=y;
25. *p=z;
26. }
27. void showdata()
28. {
29. std::cout << "value of a is : " <<a<< std::endl;
30. std::cout << "value of b is : " <<b<< std::endl;
31. std::cout << "value of *p is : " <<*p<< std::endl;
32. }
33. };
34. int main()
35. {
36. Demo d1;
37. d1.setdata(4,5,7);
38. Demo d2 = d1;
39. d2.showdata();
40. return 0;
41. }

Output:

value of a is : 4
value of b is : 5
value of *p is : 7
In the above case, a programmer has defined its own constructor, therefore the statement Demo d2 = d1; calls the copy
constructor defined by the user. It creates the exact copy of the value types data and the object pointed by the pointer p. Deep
copy does not create the copy of a reference type variable.

Differences b/w Copy constructor and Assignment operator(=)

Copy Constructor Assignment Operator

It is an overloaded constructor. It is a bitwise operator.

It initializes the new object with the existing object. It assigns the value of one object to another
object.

Syntax of copy constructor: Syntax of Assignment operator:


Class_name(const class_name &object_name) Class_name a,b;
{ b = a;
// body of the constructor.
}
o The copy constructor is invoked when the new object is The assignment operator is invoked when we
assign the existing object to a new object.
initialized with the existing object.
o The object is passed as an argument to the function.
o It returns the object.

Both the existing object and new object shares the different Both the existing object and new object shares
memory locations. the same memory location.

If a programmer does not define the copy constructor, the compiler If we do not overload the "=" operator, the
will automatically generate the implicit default copy constructor. bitwise copy will occur.

C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like
constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

C++ Constructor and Destructor Example


Let's see an example of constructor and destructor in C++ which is called automatically.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

C++ this Pointer


In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in
C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

C++ this Pointer Example


Let's see the example of this keyword in C++ that refers to the fields of current class.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }

Output:

101 Sonoo 890000


102 Nakul 59000
C++ this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in
C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

C++ this Pointer Example


Let's see the example of this keyword in C++ that refers to the fields of current class.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }

Output:

101 Sonoo 890000


102 Nakul 59000

C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static
members. In C++, static can be field, method, constructor, class, properties, operator and event.
Advantage of C++ static keyword
Memory efficient: Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it
belongs to the type, so it will not get memory each time when instance is created.

C++ Static Field


A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create
object, there is only one copy of static field created in the memory. It is shared to all the objects.

It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee
etc.
Play Videox

C++ static field example


Let's see the simple example of static field in C++.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. static float rateOfInterest;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. }
13. void display()
14. {
15. cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
16. }
17. };
18. float Account::rateOfInterest=6.5;
19. int main(void) {
20. Account a1 =Account(201, "Sanjay"); //creating an object of Employee
21. Account a2=Account(202, "Nakul"); //creating an object of Employee
22. a1.display();
23. a2.display();
24. return 0;
25. }

Output:

201 Sanjay 6.5


202 Nakul 6.5

C++ static field example: Counting Objects


Let's see another example of static keyword in C++ which counts the objects.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name;
7. static int count;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. count++;
13. }
14. void display()
15. {
16. cout<<accno<<" "<<name<<endl;
17. }
18. };
19. int Account::count=0;
20. int main(void) {
21. Account a1 =Account(201, "Sanjay"); //creating an object of Account
22. Account a2=Account(202, "Nakul");
23. Account a3=Account(203, "Ranjana");
24. a1.display();
25. a2.display();
26. a3.display();
27. cout<<"Total Objects are: "<<Account::count;
28. return 0;
29. }

Output:

201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3

C++ Structs
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects
such as Rectangle, color, Point, etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after
creation of struct.

C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.

The Syntax Of Structure

1. struct structure_name
2. {
3. // member declarations.
4. }

In the above declaration, a structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside
the curly braces, we can declare the member variables of different types. Consider the following situation:

Play Videox

1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }
In the above case, Student is a structure contains three variables name, id, and age. When the structure is declared, no memory is
allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario.

How to create the instance of Structure?


Structure variable can be defined as:

Student s;

Here, s is a structure variable of type Student. When the structure variable is created, the memory will be allocated. Student
structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will
be 2*4 = 8. The total memory occupied by the s variable is 9 byte.

How to access the variable of Structure:


The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then
the field of the structure.

For example:

1. s.id = 4;

In the above statement, we are accessing the id field of the structure Student by using the dot(.) operator and assigns the value 4
to the id field.

C++ Struct Example


Let's see a simple example of struct Rectangle which has two data members width and height.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle
4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
13. return 0;
14. }

Output:

Area of Rectangle is: 40

C++ Struct Example: Using Constructor and Method


Let's see another example of struct where we are using the constructor to initialize data and method to calculate the area of
rectangle.

1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }

Output:

Area of Rectangle is: 24

Structure v/s Class

Structure Class
If access specifier is not declared explicitly, then by default If access specifier is not declared explicitly, then by
access specifier will be public. default access specifier will be private.

Syntax of Structure: Syntax of Class:

struct structure_name class class_name


{ {
// body of the structure. // body of the class.
} }

The instance of the structure is known as "Structure The instance of the class is known as "Object of the
variable". class".

C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions
(NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly.

C++ Enums can be thought of as classes that have fixed set of constants.

Points to remember for C++ Enum


o enum improves type safety
o enum can be easily used in switch
o enum can be traversed
o enum can have fields, constructors and methods
o enum may implement many interfaces but cannot extend any class because it internally extends Enum class

C++ Enumeration Example


Let's see the simple example of enum data type used in C++ program.

1. #include <iostream>
2. using namespace std;
3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
4. int main()
5. {
6. week day;
7. day = Friday;
8. cout << "Day: " << day+1<<endl;
9. return 0;
10. }

Output:
Day: 5

C++ Friend function


If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the
function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword
friend.

Declaration of friend function in C++


1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the
program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.
Play Videox

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example


Let's see the simple example of C++ friend function used to print the length of a box.

1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }

Output:

Length of box: 10
Let's see a simple example when the function is friendly to two classes.

1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function can access the private members of both the
classes A and B.
C++ Friend class
A friend class can access both private and protected members of the class in which it has been declared as friend.

Let's see a simple example of a friend class.

1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }

Output:

value of x is : 5

In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A. Class B can access the
private members of class A.

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not
modified in call by value but it is modified in call by reference.
Let's understand call by value and call by reference in C++ language one by one.

Call by value in C++


In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the
caller method such as main().

Play Videox

Let's try to understand the concept of call by value in C++ language by the example given below:

1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }

Output:

Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value
changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in C++ language by the example given below:

1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by reference in C++

No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the function
2 Changes made inside the function is not reflected on Changes made inside the function is reflected
other functions outside the function also

3 Actual and formal arguments will be created in Actual and formal arguments will be created in same
different memory location memory location

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy