Search code examples
c++constructorderived-class

Constructor in base and derived class


Program works but I am not sure what is wrong with constructor since every time program runs it gets this error "warning: base class 'Alat' is uninitialized when used here to access 'Alat::ime' [-Wuninitialized]". I suppose it's something wrong how I called a constructor from base class but I am not sure what is problem. Really need help, tnx in advance.

#include <iostream>
#include <string>
using namespace std;

class Alat{
protected:
    string ime;
    int serBr;
    int cena;

public:   

    void setIme(string i);
    string getIme();

    void setSerBr(int sb);
    int getSerBr();

    void setCena(int c);
    int getCena();

    Alat();
    Alat(string i, int sb, int c)
    :ime(i),
     serBr(sb),
     cena(c)
    {}

    void info();


    ~Alat();
};

#include "Alat.h"

class Rucni : public Alat{
protected:
    int minGodKor;

public:    

    Rucni():Alat(ime, serBr, cena)  //I think here is problem, is it wrong called?    
    {}

    int getminGodKor();
    void setminGodKor(int min);

    void info();

    ~Rucni();

};

Solution

  • Let the child default constructor call the default parent constructor, and create another child constructor with parameters to call the corresponding one of the parent:

    #include <string>
    
    using std::string;
    
    
    class Alat
    {
    protected:
        string ime;
        int serBr;
        int cena;
    
    public:   
    
        void setIme(string i)
        {
            ime = i;
        }
    
        string getIme()
        {
            return ime;
        }
    
        void setSerBr(int sb)
        {
            serBr = sb;
        }
    
        int getSerBr()
        {
            return serBr;
        }
    
        void setCena(int c)
        {
            cena = c;
        }
    
        int getCena()
        {
            return cena;
        }
    
        Alat()
        {
        }
    
        Alat(string i, int sb, int c) : ime(i), serBr(sb), cena(c)
        {
        }
    
        ~Alat()
        {
        }
    };
    
    
    class Rucni : public Alat
    {
    protected:
        int minGodKor;
    
    public:    
    
        Rucni() // implicit call of the parent default constructor
        {
        }
    
        Rucni(string i, int sb, int c) : Alat(i, sb, c) // explicit call of the corresponding parent constructor
        {
        }
    
        int getminGodKor()
        {
            return minGodKor;
        }
    
        void setminGodKor(int min)
        {
            minGodKor = min;
        }
    
        ~Rucni()
        {
        }
    };
    
    
    int main()
    {
        Rucni r;
    
        return 0;
    }