Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...