Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would someone provide an empty default constructor for a class?

Tags:

class complex {   float x,y; public:   complex(){} //constructor with no arguments //what is use of giving such constructor     complex(float z){x=y=z;}//constructor with 1 argument.     complex(float real,float imag)     {x=real;y=imag;}     friend complex sum(complex,complex);      friend void show(complex); };  complex sum(complex c1,complex c2) {   complex c3;   c3.x=c1.x+c2.x;   c3.y=c1.y+c2.y;   return (c3); }  void show (complex c) {   cout<<c.x<<"+j"<<c.y<<"\n"; } int main() {   complex p,q,r;   p=complex(2.5,3.9);   q=complex(1.6,2.5);   r=sum(p,q);    cout<<"p=";show(p);   cout<<"q=";show(q);   cout<<"r=";show(r);   return 0; } 
like image 799
Trupti Avatar asked Dec 19 '10 08:12

Trupti


People also ask

What is the purpose of empty constructor?

An empty constructor provides us with the instance of an object. We might need to use setters to set the necessary properties for it. The empty constructor can be used when we want to make sure that any instance created is always valid and the variables are initialized.

Why does a class need to have a default constructor?

What is the significance of the default constructor? They are used to create objects, which do not have any specific initial value. Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.

What is the purpose of an empty constructor in C#?

If you declare an empty constructor, the C# compiler will not dynamically generate a parameter-less constructor. If you do not use an access modifier with the constructor, it will also become a private constructor by default. Using the private keywords makes it obvious for developers by explicitly stating the type.

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members.


1 Answers

When you declare a class without any constructors, the compiler provides a default constructor (on demand) that default-initializes the members. (Note that default-initialization on built-ins such as float does nothing). However, once you define any constructor for the class, the default constructor is no longer automatically provided. Hence you must define your own default constructor if you still want one.

like image 80
user470379 Avatar answered Oct 03 '22 09:10

user470379