Jump to content

C++: How to access base-class constructor from derived class?

- - - - -

  • Please log in to reply
4 replies to this topic

#1
arnes99

arnes99

    Learning Programmer

  • Members
  • PipPipPip
  • 32 posts
I'm having problem using base-class constructor from derived-class constructor. In derived-class constructor I'm having couple of arguments and some of them I want to pass to the base-class constructor and some use normally.
The problem is that it doesn't assign to the base-class variables - ONLY to the derived-class variables! If someone know how to simply do this I would be thankful for info. I've tried to search net and found some site with info on how to use them.
Something like this:
...
B(int a, int b, int c) : A(a){ //<--- B - Constructor in a derived class, A - base-class constructor
  someVar1 = b;
  someVar2 = c;
}
But it doesn't work. a variable remains unset.

#2
abzero

abzero

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 217 posts
That's the syntax, can you post full definitions for both classes?

#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript
You need to pass it as an argument to the constructor, which must assign it.

class A {
 private:
  size_t var_a;

 public:
    A (size_t a) : var_a(a) { }
};

class B : public A {
 private:
  size_t var_b, var_c;

 public:
  B (size_t a, size_t b, size_t c) :
      A(a), var_b(b), var_c(c)
  {
  }
};

Are you doing this?
sudo rm -rf /

#4
arnes99

arnes99

    Learning Programmer

  • Members
  • PipPipPip
  • 32 posts
Thank you dargueta. You did clarify this and it works now. Your example works. I think this topic can be closed now.

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript
Oh, good. I finally did something right. :D
sudo rm -rf /




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users