C++ Programming - Constructors and Destructors - Discussion

Discussion Forum : Constructors and Destructors - General Questions (Q.No. 8)
8.
Which of the following statement is incorrect?
Constructor is a member function of the class.
The compiler always provides a zero argument constructor.
It is necessary that a constructor in a class should always be public.
Both B and C.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
34 comments Page 4 of 4.

Yudi said:   7 years ago
Using singleton the constructor could be private.

e.g:
class TestSingleton{

private:
static TestSingleton * mInstance;
int mValue;
TestSingleton() {
mValue = 0;
}
public:

static TestSingleton *get_instance(){
if (TestSingleton::mInstance == nullptr){
TestSingleton::mInstance = new TestSingleton();
}
return TestSingleton::mInstance;
}

void set(int value){
this->mValue = value;
}

int get(){
return this->mValue;
}
};
TestSingleton *TestSingleton::mInstance = nullptr;


int main()
{
TestSingleton * sin = TestSingleton::get_instance();
TestSingleton * sin2 = TestSingleton::get_instance();
sin->set(10);
printf("value = %d\n", sin->get());
printf("value = %d\n", sin2->get());
}

Answer C is wrong (It is necessary that a constructor in a class should always be public.)

K Goyal said:   7 years ago
B is wrong because if we have defined one or more argument constructor then the compiler will never provide zero argument constructor we have to provide it explicitly.

#include <iostream>
#include <string>
using namespace std;

class name
{ public:
name(string s)
{cout<<s<<endl;
}
};

int main()
{ name s1("abc");
name s2; // complier will show an error -> we must add constructor name(){ ...} too.
return 0;
}

Wild said:   4 years ago
Constructor is a member function!

Arjun Mandavkar said:   4 years ago
@Amit Kumar Giri.

Your Explanation is very accurate. Thanks.


Post your comments here:

Your comments will be displayed after verification.