"Taran" <> skrev i meddelandet
news: oups.com...
> Hi All,
>
> I tried something with the C++ I know and some things just seem
> strange.
>
> consider:
>
> #include <iostream>
>
> using namespace std;
>
> class base
> {
> public:
>
> base();
> void some_func_2();
> private:
> void some_func();
> };
>
> ///////////////////////////
> base::base()
> {
> cout<<"base constructor"<<endl;
> }
> ///////////////////////////
>
> void base::some_func()
> {
> cout<<"base some func"<<endl;
> }
> ///////////////////////////
>
> void base::some_func_2()
> {
> cout<<"base some_func_2"<<endl;
> }
> ///////////////////////////
>
> class derived: public base
> {
> public:
> void some_func();
> static void some_func_2();
>
> };
>
>
> void derived::some_func()
> {
> cout<<"derived some func"<<endl;
> }
> ///////////////////////////
>
> void derived::some_func_2()
> {
> cout<<"derived some_func_2"<<endl;
> }
> ///////////////////////////
>
> void main()
> {
> base b;
> b.some_func_2();
> base::base();
> derived d;
> d.some_func();
> derived::some_func_2();
> d.some_func_2();
>
> derived *pd;
> pd = reinterpret_cast<derived*>(new base());
>
> // derived *pd;
> // pd = new base(); /// This will cause errors if
> uncommented.
>
> }
>
> Here's the output:
>
> base constructor
> base some_func_2
> base constructor
> base constructor
> derived some func
> derived some_func_2
> derived some_func_2
> base constructor
>
>
> My problems here are that
>
> 1. I understood that derived class cannot increase the scope of the
> base class methods. In this case 'derived' increased the scope of
> the
> base class private method 'some_func' by making it public and the
> scope
> of base class 'some_func_2' by making it static. Is my understading
> incorrect or there's something wrong?
The functions defined in derived hides the functions in the class
base. It's a another set of functions, with the same names. It doesn't
affect the functions of the base class.
>
> 2. The constructor for the base class can be called explicitly, even
> though I cannot do anything more with that. i fail to understand why
> should it be allowed. Are there any special circumstances where this
> is
> used?
Not very useful, but also not specifically forbidden by the standard.
Why should it be?
>
> 3. Base class handle can take derived class objects but not the
> other
> way around.
In C++ it is called a pointer, not a handle. A base class pointer can
point to a derived class, because there is a base part in the derived
class. A derived class can act as its base, because it has inherited
(some of) its properties.
> Casting will remove this error but why doesn't implicit
> cast like the previous one work?
Casting doesn't remove the error, it just tells the compiler to shut
up -- "Trust me, I know what I'm doing!".
If that isn't really true, all kinds of nasty things are likely to
happen.
Bo Persson