"Extend" Struct in C++

14,652

Solution 1

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)

Solution 2

Your parent and daughter are essentially the same type besides their initial class values. The same goes for grandson and son.

Why not use a constructor for that task?

struct parent
{
    parent () : foo(), bar() {}
    parent (int the_foo, int the_bar) 
      : foo(the_foo), bar(the_bar) {}
    int foo;
    int bar;
};

struct son : public parent
{
    son () : parent(10,20), foobar(foo+bar) {}
    son (int the_foobar) 
      : parent(10,20), foobar(the_foobar) {}
    int foobar;
}

int main ()
{
  parent p;
  parent daughter(1,3);
  son s;
  son grandson(10000);
}
Share:
14,652
AnOptionalName
Author by

AnOptionalName

I am an upcoming programmer who enjoys random technical subjects. Some interests include: puzzles, game development, and simulations

Updated on June 04, 2022

Comments

  • AnOptionalName
    AnOptionalName almost 2 years

    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);
    }