vendredi 22 novembre 2019

problem with derived class in c++ with no data member

So i'm learning c++ inheritance and facing problem with the following exercise to create a based class A and a derived class B with certain requirement. I have my answer written down below, but there's seem some problem with it. and I have a few question at the end of this post also. thanks for answering.

enter image description here

class A {
    private:
        int x;
    protected:
        A (): x(0) { } 
        A (int n): x(n) { }
        int get() const {return x;}
    public:
        virtual void foo() = 0;
};

enter image description here

class B : public A {
    public:
        B (): { A(); }
        B (int n): { A(n); }
        virtual void foo() { std::cout << get();}
};

My Question is:

  1. Is my code correctly written in the first place?
  2. since x is private in A, B wouldn't be able to inherit that date member. So, how is B able to invoke the constructor?
  3. pretty sure that A is an abstract class, but is B an abstract class too?

Aucun commentaire:

Enregistrer un commentaire