Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote