0

this is a complicate situation:
i have A class by type

Base
{
Btype* m_b;
};

and a class

DerivBtype:public Btype
{
..
}

and this class

class derived :public base
{
}
and i want to behave m_b as a derived class
i used this approach
m_b=new derived ;
and cast m_ b to derived where is neede is ther a simplere way to do this?

2
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by jalalsad
0

I didn't get what u are trying to do. But let me explain a bit of inheritance

class Base
{
/*members*/
};

class Derived:public Base
{
/*members*/
};

Base *bptr = new Derived();
/*or if u need only base object*/
bptr = new Base();

But using bptr u wont' be able to access the mebers of Derived class untill and unless they are declared in the Base class as virtual and overridden in the derived class.

Read on inheritance.

Edited by dkalita: n/a

0

themethod can be defined virtual but is there a way to declare data member not function virtual?this is my problem.

Edited by jalalsad: n/a

0

the data variables can be defined virtual but is there a way to declare dat member not function virtual?this is my problem.

If u dont declare them as virtual and u try to access the derived class member then it will invoke the base class member only.
e.g.

class base
{
public:
   virtual void fun()
   {
         /*do something*/
   }
};
class derived:public base
{
public:
   void fun()
   {
    /*do something else*/
   }
};

base *bptr = new derived();
bptr->fun();
/*this will invoke the derived class member.(derived::fun())*/
/*But if u remove the keyword virtual in base class, it will invoke the base class member(base::fun()).*/

Edited by dkalita: n/a

-1

thanks for yor replies
excuse me .maybe i cant describe it well. i mean if i have a variable not a function in the base class. and then if i want to use a derived instance of that variable not method in the derived class whts the best way ?
i use these method but i amnot sure

class ClassVar
{
...........
}
class DerivedClassVar:public ClassVar
{
.........
}
class BaseContainer
{

ClassVar* m_meber;//variable

}
and i want to treat in below class as derived class with this meber


class DerivedBaseContainer:public BaseContainer
{


DerivedBaseContainer()
{
//my soloution::
m_meber=new DerivedClassVar;
DerivedClassVar* m_CastMem=dynamic_cast< DerivedClassVar *>(m_member)

m_CastMem->......................

}


}

thanks

{


}

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.