Search code examples
c++inheritancestructextend

"Extend" Struct in C++


I say "extend" because after a google search I'm not sure that is the proper name for what I'm trying to accomplish.

Basically what I'm trying to do is create a struct (just for fun, let's also include classes in this question) with some blank variables in it, then make another struct or class that carries on where the parent left off, filling in those variables.

So something like this:

struct parent{

    int foo;
    int bar;
};

struct daughter : parent{
    foo=1;
    bar=3;
};

struct son : parent {
    foo=10;
    bar=20;

    int foobar;
};

and later on, I might need to branch out this tree further:

struct grandson : son {
    foo=50;
    bar=900;
    foobar=10000;
};

What would be the correct way to go about this?

EDIT:

@Everyone: So, I can explain what I'm trying to do, and you can counter it with better ways, and who knows, maybe those ways are much better. However, first, right off the bat, I'm just curious if what I'm asking is possible...

And something I left out:

struct parent{
    int foo;
    int bar;
    int foobar;

    int add(int x, int y){
        return x+y;
    };

struct son : parent {
    foo=12;
    bar=13;
    foobar=add(foo,bar);
}

Solution

  • I think you may want to use constructors to initialize values like that. Something like this:

    struct daughter : public parent {
       daughter() {
          foo=1;
          bar=3;
       }
    };
    

    (btw I know the 'public' keyword isn't necessary, I included it only because I like to keep my intent explicit; otherwise I always wonder later if I just forgot to specify it)