views:

115

answers:

3

I received homework to make program without casting using constructors so this is my code, I have two classes:

class Base {
protected:
    int var;
public:
    Base(int var = 0);
    Base(const Base&);
    Base& operator=(const Base&);
    virtual ~Base(){};
    virtual void foo();
    void foo() const;
    operator int();
};

class Derived: public Base {
public:
    Derived(int var): Base(var){};
    Derived(const Base&);
    Derived&  Derived::operator=(const Base& base);
    ~Derived(){};
    virtual void foo();
};

here two of my functions of Derived:

Derived::Derived(const Base& base){
    if (this != &base){
        var=base.var;
    }
}

Derived&  Derived::operator=(const Base& base){
    if (this != &base){
        var=base.var;
    }
    return *this;
}

but I have an error within context when I call these rows

Base base(5);
Base *pderived = new Derived(base);  //this row works perfectly
Derived derived = *pderived;  // I think the problem is here

thanks for any help

A: 

There is an error (VS2010)

error C2248: 'Base::var' : cannot access protected member declared in class 'Base'

at the line

var=base.var;

Alexey Malistov
Right, because `base` might have type `class Other : public Base {};`. `Derived` isn't in the inheritance chain for `Other`, so it has no access to protected members.
Ben Voigt
A: 

You can only access protected members from another object if that object is of the same type as the object that is trying to access it. In your example the constructor and assignment operator both take in a const Base& so there is no guarantee that the actual object will be of type Derived.

Troubadour
A: 

Derived needs to delegate copying of Base members to Base::operator=, instead of trying to put its grubby little hands on the protected members of another object.

Ben Voigt