Search code examples
c++inheritancestructpublicprotected

C++ Inheritance "Ignored"


I have this block of code:

struct Road_Primitive {
public:
    Road_GPU_Point A;
    Road_GPU_Point B;
    Road_GPU_Point C;
};

struct Road_Primitive_4P : public Road_Primitive {
    Road_GPU_Point D;
};

struct Road_Primitive_3P : public Road_Primitive{
};

And in one of my classes I have a Road_Primitive*, which is initialized with either new Road_Primitive_4P or new Road_Primitive_3P, depending on other factors.

However, this section of code gives me an "class Road_Primitive has no member D":

Road_Primitive* pmtv_Prospect = new Road_Primitive_4P;
pmtv_Prospect->D.X = pch_Rightmost->GPU_Primitive->B.X;

However, if I declare Road_Primitve with protected members, the error turns into something like: "Member B is inaccesible"

Any suggestions?


Solution

  • Well, class Road_Primitive hasn't any member D. Every expression is interpreted in light of the declared types of all its sub-expressions, as evaluated by the compiler. The fact that pmtv_Prospect currently points to a Road_Primitive_4P at some point during the execution doesn't factor in -- if you access that Road_Primitive_4P via a Road_Primitive * then you have access only to those members declared by class Road_Primitive.

    If you want to be able to access Road_Primitive_4P.D, then you must do so via a value of (declared) type Road_Primitive_4P. Thus, you could write

    Road_Primitive_4P* pmtv_Prospect = new Road_Primitive_4P;
    pmtv_Prospect->D.X = pch_Rightmost->GPU_Primitive->B.X;
    

    Of course, in that case you cannot assign pmtv_Prospect to point to a Road_Primitive_3P, but that's really the whole point. If you could make it point to a Road_Primitive_3P, which has no member D, then it would not be safe to access the referent's D.