c++constructorfriend-class

Why can I not instantiate a class whose constructor is private in a friend class?


I have two classes; Salary that is intended to hold information and calculations regarding the salary of an employee and Employee that has an object of type class Salary and some members like name and address of the employee...

Now the program compiles correctly!

*** Another thing in main if I declare an object this way:

Employee emp; // ok
Employee emp{}; // error?

Solution

  • Because you don't provide a constructor for Employee the braces in your initialization Employee emp{}; will perform an aggregate initialization, which essentially means that each member is initialized one-by-one using the default rules, in the context of main(). Since main() doesn't have access to the Salary constructor, it fails.

    As others have pointed out, adding an Employee default constructor will resolve your problem:

    class Employee {
        public:
            Employee() = default;
            std::string name_;
            Salary sal;
    };