Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Question about default constructor [duplicate]

Tags:

c++

class

What does it mean to call a class like this:

class Example
{
 public: 
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

like image 599
Daniel Avatar asked Jan 14 '09 19:01

Daniel


People also ask

Can you have multiple default constructors?

There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.

Is default copy constructor shallow copy?

The default constructor does only shallow copy. Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new memory locations.

What happens if you use the default copy constructor for vector?

The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.

Is default constructor automatically generated?

If any constructor is explicitly declared, then no default constructor is automatically generated. If a virtual destructor is explicitly declared, then no default destructor is automatically generated.


1 Answers

Currently you are trying to call the default constructor like so.

Example ex();

This is not actually calling the default constructor. Instead you are defining a function prototype with return type Example and taking no parameters. In order to call the default constructor, omit the ()'s

Example ex;
like image 187
JaredPar Avatar answered Sep 23 '22 20:09

JaredPar