Reputation: 21
class Base{
public:
float a,b;
};
class Derived:public Base{
public:
int someInteger, otherInt;
void assignNthElement(vector<Base> &myArray,int i){
this=myArray[i-1];//??? How ???
}
void simpleMethodOfAssigningNthElement(vector<Base>&myArray,int i){
a=myArray[i-1].a;
b=myArray[i-1].b;
}
};
How to directly copy values describing Base class within derived class from myArray? Maybe it's better to do it like it's done in "simpleMethodOfAssigningNthElement"? Which is faster?
Upvotes: 1
Views: 80
Reputation: 2954
You can use some C-hacks, but it is bad way. Best way is simpleMethodOfAssigningNthElement.
If you want you can overload operator=
for Derived
class.
class Base{
public:
float a,b;
};
class Derived : public Base{
public:
int someInteger, otherInt;
void assignNthElement(vector<Base> &myArray,int i){
this = myArray[i-1];// It's OK now
}
const Derived & operator=(const Base &base){
a=base.a;
b=base.b;
}
};
Upvotes: 0
Reputation: 206646
You cannot assign an Base class object to an Derived class object as in assignNthElement()
that will give you a compilation error.
Note that the reverse is allowed, ie: you can assign an Derived class object to an Base class object, but that would end up slicing up the members of the derived class object. The phenomenon is called Object Slicing.
Upvotes: 1
Reputation: 11232
You can not do it the way you are trying in assignNthElement
, it needs to be implemented like simpleMethodOfAssigningNthElement
only.
Upvotes: 1