Constructor

I have read some where that when we use a parameterized constructor it is a must to define a default constructor explicitly. Is this true???


Thanks in advance!!!


Last edited on
No. Only if you actually need it. For example, if the class is going to be used as an element in a container, then you do need it.
closed account (S6k9GNh0)
That confused me so I'll explain it this way: When you make a class, it comes with a default constructor. But the reason it's called the default constructor is because it's only made if no constructor has been specified therefor it's made by default. Get it? If you declare your own constructor, you need to remake the default constructor or the constructor with no parameters.
Last edited on
Even I was thing the same. Quite surprisingly the following is working even though I have not explicitly given the constructor.
#include<iostream>
using namespace std;
class A
{
int j;
public:
A(int i)
{j=i;}
void display();
};
void A::display()
{cout<<j;}
int main()
{
A A2(10);
A2.display();
}
closed account (S6k9GNh0)
Oh yeah? Try calling this!
 
A bob(); 

Last edited on
This will require a default constructor...
But if I require initializing objects by passing a value .....then????
closed account (S6k9GNh0)
If what I posted confused you here's why: If you don't declare your own default constructor, you can call A bob(); because it's created by default. Your example above where you passed parameter integer i worked just fine right? What's not to understand?
It is working for me too....This means if I dont define a default constructor, my program will work until unless I try to create an object like thisA bob();
The compiler provides a default constructor ONLY if you do not define your own custom (non-copy) constructor(s). If you provide a custom constructor, then the compiler does not give you a default constructor; you might write it if you need it.

Passing objects by value to functions requires a copy constructor, not a default constructor.

BTW, A bob(); will not compile with or without a default constructor. Google C++ most vexing parse.

Topic archived. No new replies allowed.