c++ - Access child struct values in vector -
this question has answer here:
- what object slicing? 15 answers
i have object structs this:
struct object { string type; color c; float ambient, diffuse; }; struct sphere: object { point center; float radius; }; struct square: object { point loc; float len; };
and have vector filled sphere , square structs:
vector<object> objs; sphere sp = //sphere stuff square sq = //square stuff objs.push_back(sp); objs.push_back(sq);
i can access values in parent struct fine, having trouble figuring out how access values in sphere , square structs. doing right now:
cout << objs.at(i).type << endl; //this works cout << objs.at(i).center.x << endl; //not working
does know how this?
you can't, don't exist more. not storing square
s or sphere
s in vector
, storing object
s. should read what object slicing?.
that said, if instead store pointers object
s, std::vector<object*>
pass pointers objects of derived types. how know element in vector
square
, sphere
. whole purpose of having base class provide interface functionality want, through virtual
function, derived classes implement in different ways:
struct base { virtual void foo() { std::cout << "foo in base\n"; } }; struct derived1 : base { void foo() override { std::cout << "foo in derived1\n"; } }; struct derived2 : base { void foo() override { std::cout << "foo in derived2\n"; } }; derived2 d; base* b = &d; b->foo(); // prints "foo in derived2\n"
that said, square*
object*
, use static_cast<square*>(objp)
if know sure square
, , dynamic_cast<square*>(objp)
if not (it return null pointer if wrong). having indicates bad design though!
also, please reconsider use of considered bad practices: using namespace std;
, endl
(those links explanations).
Comments
Post a Comment