c++ question: What is the reason why this class doesn’t allow instantiation of a
ID: 3693331 • Letter: C
Question
c++ question:
What is the reason why this class doesn’t allow instantiation of an object? __________ (2 points)
// Galaxy.cpp
class Galaxy // class definition
{
private: string name; // member field
Galaxy(string name) // constructor
{ this->name=name; }
public:
string get () // getter member method
{ return name; }
void set(string name) // setter member method
{ this->name=name; }
};
Select one:
a. There are syntax errors in the code.
b. It is because the name field is declared as private.
c. It is because the constructor is declared as private.
d. None of the choices
Explanation / Answer
Answer: It is because the constructor is declared as private.
There are many scenarios for having private constructors. Few of them are:
Restricting object creation
For singleton patterns
Restricting certain type of constructor (e.g. copy constructor, default constructor)
The above code will create an object if we do lile this
class Galaxy // class definition
{
private:
string name;// member field
public:
Galaxy(string name)// constructor
{
this->name=name;
}
string get ()// getter member method
{
return name;
}
void set(string name)// setter member method
{
this->name=name;
}
};
int main()
{
string name;
Galaxy g(name);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.