Stefan
Stefan

Reputation: 113

Error calling the constructor

I'm a little new with OOP and I have a small problem with a constructor inside of a derived class.

I have the following code:

class Functionar{
    protected:
        char nume[20];
        int cnp;
    public:
        Functionar(char *n,int c){strcpy(nume,n); cnp=c;}
        virtual void Afisare();
};

void Functionar::Afisare()
{
    cout<<"Nume: "<<nume<<endl<<"CNP: "<<cnp<<endl;
}

class Permanent:public Functionar{
    protected:
        int salariu;
        int nrorelucrate;
    public:
        //Permanent(char *n,int c,int s,int nr): Functionar(char *n,int c),salariu(s),nrorelucrate(nr){}
        Permanent(char *n,int c,int s,int nr)
        {
            Functionar(char *n,int c);
            salariu=s;
            nrorelucrate=nr;
        }
        //void Afisare();

};
main()
{
    Functionar Claudiu("Claudiu",495);
    Claudiu.Afisare();
}

Sorry for the variable and function names. They might look a little strange. The idea is that I want to create a constructor in the derived class using the base constructor for nume and cnp.

I have a couple of errors:

In constructor 'Permanent::Permanent(char*, int, int, int)':
[Error] no matching function for call to 'Functionar::Functionar()'
[Note] candidates are:
[Note] Functionar::Functionar(char*, int)
[Note] candidate expects 2 arguments, 0 provided
[Note] Functionar::Functionar(const Functionar&)
[Note] candidate expects 1 argument, 0 provided
[Error] expected primary-expression before '(' token
[Error] expected primary-expression before 'char'
[Error] expected primary-expression before 'int'
C:\Users\Stefan\Desktop\Probleme Culegere POO\problema12.cpp    In function 'int main()':
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

I don't understand why there is no matching for 'Functionar::Functionar()'. Thank you.

Upvotes: 1

Views: 493

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

You should use a constructor's initializer list to call constructor of the base class(especially for ctors with arguments), such as:

Permanent(char *n, int c, int s, int nr) : Functionar(n, c), salariu(s), nrorelucrate(nr) {}

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

Use

Permanent(char *n,int c,int s,int nr) :
        Functionar(n,c) 
        //your other variables go here
{
}

Without the initializer list, a default constructor is required because the class attempts to default-initialize the its base.

Even if you did have a default constructor for Functionar, your version would just create a temporary object that would get destroyed after the ; and not initialize the base as you would expect.

Upvotes: 2

Related Questions