简体   繁体   中英

How to access object of a derived class by base class reference in c++?

I would read The following lines in C++:The complete reference Book. I Did no get clear idea with that.

References to Derived Types

Similar to the situation as described for pointers earlier, a base class reference can be
used to refer to an object of a derived class. The most common application of this is
found in function parameters. A base class reference parameter can receive objects of
the base class as well as any other type derived from that base.

I Have doubt with than following code:

#include<iostream>

using namespace std;


class base
{
protected:
    int i;
public:
    void seti(int num){i=num;}
    int geti(){return i;}
};

class derived:public base
{
protected:
    int j;
public:
    void setj(int num){j=num;}
    int getj(){return j;}
};


void refe(base &ob)
{
    ob.seti(1);
    ob.setj(2);
}

int main()
{
   derived d;
   refe(d);

   cout<<d.geti();
   cout<<"\n"<<d.getj();

   return 0;
}

When i compile The code It will through the following error:

D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: 'class base' has no member named 
'setj'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 5 second(s)) ===

and i also cast like this in function refe() ((derived *)ob).setj(2); this also shows following error:

D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: invalid cast from type 'base' to 
type 'derived*'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 3 second(s)) ===|

So please explain this lines in that book.

You can call only virtual function of derived class from base class reference see this,

#include<iostream>

class Base
{
public:
    virtual void fun()
    {
        std::cout<<"Base";
    }
};

class Derived:public Base
{
public:
    void fun()override
    {
        std::cout<<"Derived";
    }
};

void myfun(Base &ob)
{
    ob.fun();
}

int main()
{
    Derived ob;
    myfun(ob);
    return 0;
}

Output:

Derived
Process returned 0 (0x0)   execution time : 0.266 s
Press any key to continue.

And i also cast like this in function refe() ((derived *)ob).setj(2); this also shows following error:

Cast to ((derived &)ob).setj(2); this will work because it is not pointer it is reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM