Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error compilation because private member

Tags:

c++

scheduler

My main class Task has a private member:

private:
    Task();

I add a derivate class Scheduler with herance of class Task:

class Scheduler : public Task {
    friend class Task;`

I create a file Scheduler.cc to implement the constructor of class derivate Scheduler:

Scheduler::Scheduler() {
    //nothing here.
}

I try compile with the constructor Scheduler in blank but I received an compilation error that I am not understanding the relation because my constructor Scheduler is in blank:

/tmp/PROJETO/T1/booos-t1/lib/Task.h: In constructor ‘BOOOS::Scheduler::Scheduler()’: /tmp/PROJETO/T1/booos-t1/lib/Task.h:41:2: error: ‘BOOOS::Task::Task()’ is private Scheduler.cc:13:22: error: within this context make[1]: ** [Scheduler.o] Erro 1

I would like understand my problem because I am not trying to access private member of class Task in my Scheduler constructor.

like image 357
Ronaldo João Borges Avatar asked Dec 25 '22 21:12

Ronaldo João Borges


2 Answers

Since Task is a base class of Scheduler,

Scheduler::Scheduler() {
  //nothing here.
}

is equivalent to

Scheduler::Scheduler() : Task() {
  //nothing here.
}

Since Task::Task() is private, the compiler cannot process that code.

You can put the default constructor of Task in protected section to get rid of this error. That way, a client cannot create an instance of Task using the default constructor but the sub-classes of Task can use its default constructor.

protected:
      Task();
like image 190
R Sahu Avatar answered Jan 12 '23 20:01

R Sahu


Task() is not a private member, it's a private default constructor.

Your derived class cannot access your private default constructor. You need to make it protected, or, if you have another costructor available, use this one:

class Task
{
public:
    Task( int i );

private:
    Task();
};

Scheduler::Scheduler()
{ // does not compile, equivalent to the next one
}

Scheduler::Scheduler() : Task() 
{ // does not compile
}

Scheduler::Scheduler() : Task(3) 
{ // does compile!
}
like image 41
jpo38 Avatar answered Jan 12 '23 20:01

jpo38