Two C++ questions

Started by
12 comments, last by NeXius 21 years ago
Okay, the answer to my question is you have to tell the base class what values to put into the constructor.

  class derived : public base {    derived() : base(1, 4.0) {    }}  


you can''t do what you suggest because derived doesn''t have a constructor of type derived(int, double) . If you made one that would be another situation entirely!
Advertisement
quote:
1. Why can''t member variables of a derived class override member variables from the base class that have a greater type in the inheritence tree?


Why would you want to? It is not very safe. Besides, you can use union you know. It is all about planning.

quote:
2. Why can''t constructors be inherited directly??? I''m always forced to do this:

class B{    B::B() : A()    {}};  



Constructors are for setting things up when creating the class. If you could inherit that then you basically would mess everything up faster than you can say Slartibartfast. That is automatically called when the class is created. Having two initializers would confuse the program.
neXius if you have a *X member variable and put a derived *Y in it then yes you can only get at the member variables and functions declared in class X. If you design your class hierarchy well you should be able to get away with that and still get the desired behaviour just by overriding virtual functions. Another way as someone mentioned is to use runtime casting and type checking but more often than not that''s a workaround for a bad design.

Also you keep using examples like this:

class A {public:  A() {};};class B : public A {public:  B() : A() {};}; 


I realize these are just dummied up examples, but do you realize that this code accomplishes the exact same thing:

class A {};class B : public A {}; 


This is for a couple reasons. If you don''t declare a default constructor for A or B the compiler creates one for you. Also, when you construct a derived class it first constructs all the bases classes with their default constructors. So in some specific cases you do in a sense inherit constructors, but it isn''t done in general.

As for why constructors aren''t inherited in general: I can''t give you very concrete reasons but in my experience derived classes are designed in such a way that it really makes no sense to inherit constructors. The derived class often needs additional information or needs additional functionality for its constructor that simply isn''t provided by the base class. That''s why you''re creating a derived class, to have that extra functionality.
Yes... I see.

I knew there was a reason

Thanks everyone
MSN: stupidbackup@hotmail.com (not actual e-mail)ICQ: 26469254(my site)

This topic is closed to new replies.

Advertisement