Reputation: 31
I am in beginner stage of C++. Suppose I have a base class and a derived class:
class Base{
....
}
class Derived:public Base{
....
}
Now I have two vectors as follows, I will perform some operations to some create base and derived objects and push these objects back to their corresponding vectors respectively:
std::vector<Base*> baseVector
std::vector<Derived*> derivedVector
I want to point each of the element(object) of derivedVector to each of the element(object) of the baseVector. Suppose derivedVector[2] will have a pointer to baseVector[2] so that at any time I can access the base object from my derived object. How should I do this?
Upvotes: 2
Views: 120
Reputation: 27133
I think this is the important part of your question:
... so that at any time I can access the base object from my derived object.
And the answer is fairly simple. With inheritance, the derived object can already access its base object. That's the whole point of inheritance.
You can keep it simple:
class Base{
SomeBaseFunction();
}
class Derived : public Base{
// Do not add a Base* here.
}
int main() {
Derived *derived_object = new Derived();
derived_object->SomeFunction(); // this works.
}
You should think more clearly about your vector
s here. You probably only need one vector, not two. Also, you should probably deal with vector<Derived>
, not vector<Derived*>
.
int main () {
Derived derived_object; // don't use `new` here, it's just awkward
vector<Derived> vector_of_objects;
vector_of_objects.push_back(derived_object);
}
In modern C++, whether you're a beginner or an expert, you shouldn't use *
or new
very often.
Upvotes: 0
Reputation: 31
Hi thanks for your response. I have figured out what I needed to do. Not sure if its the smartest way, if not please suggest me.
Here is how I did it:
class Base{
SomeBaseFunction();
}
class Derived:public base{
//I have put a pointer of base type here
base *basePointer;
}
Now in the main function where I basically populate the base and derived vector, I do the following:
derivedObject->basePointer = baseObject;
Now I can access the base properties as follows:
derivedObject->basePointer->SomeBaseFunction();
Upvotes: -1
Reputation: 26164
It's not very clear what you mean, but if I understand correctly you want to put pointer to your Derived
object in two vectors. You can achieve it this way:
baseVector[2] = derivedVector[2] = new Derived();
Upvotes: 3
Reputation: 172
See if you want to use base list to contain derived object pointers then it is ok. but you can't use derived list to hold base pointers.
may be you want something like.
Base * pBase = new Base();
Derived *pDerived_1 = new Derived();
// or
Base *pDerived_2 = (Base *)new Derived();
// this can be anytime casted back
Derived *pDerived_3 = (Derived*)pDerived_2;
// you can also push them into base vector
lstBasePtr.push_back(pBase);
lstBasePtr.push_back(pDerived_1);
lstBasePtr.push_back(pDerived_2);
lstBasePtr.push_back(pDerived_3);
Upvotes: 0