#Can I reference subclasses as a pointer to a superclass in another class?

22 messages · Page 1 of 1 (latest)

spice oak
#
class foo
{
public:
  int x;
  int y;
};
class bar : public foo
{
public:
  std::string str;
};
class moo : public foo
{
public:
  bar *left; // Can be either foo or bar.
  bar *right;
  char c;  
};```
Can I do that? Else, what am I supposed to do?
spare pecanBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

deft canopy
#
bar *left; // Can be either foo or bar.

this comment is false, it can only be a bar*

#

if it can either be a foo or bar object have a base class pointer

spice oak
deft canopy
#

yeah, that would be the only way if it can be both

spice oak
#

Thanks a lot.

#

!solved

spare pecanBOT
#

Thank you and let us know if you have any more questions!

spice oak
# deft canopy yeah, that would be the only way if it can be both

Sorry to bother again, but I didn't want to polute with another post. I have this class:

class astAdd : public astNode
{
public:
    astNode *left;  // uninitialized
    astNode *right; // uninitialized
    bool isEvaluable = left->isEvaluable && right->isEvaluable;
    void print()
    {
        std::cout << '(';
        left->print();
        std::cout << '+';
        right->print();
        std::cout << ')';
    }
    long long int eval()
    {
        return left->eval() + right->eval();
    }
    astAdd(astNode *__left, astNode *__right)
    {
        left = __left;
        right = __right;
        isEvaluable = left->isEvaluable && right->isEvaluable;
    }
};```
And I'd like to know how I'm supposed to initialize them. I've tried with `astNode()`, but that obviously didn't work as I intended (initializing with default values).
#

Initialize the first two astNode*, that is.

deft canopy
#
__left

this is not a legal name btw

spice oak
deft canopy
#

well it's more 2 underscores is reserved

spice oak
#

Using only 1 would be bad practice?

deft canopy
#

well, depending on the context it's reserved as well

#

or atleast an underscore and a capital

#

and uderscores in global namespaces I believe

#

but yeah a few things use initializer lists instead of setting it in the constructor body

#

make eval const

#

well the reason it's complaining about unitialized values is cause they technically are till the body gets run

spice oak
#

That makes sense.