I have to write definition of the code below. I undarstand some basics of OOP Cpp, I know what is *x or &x, but that’s not enough… The main fact is that i cant understand line B* p = new D, m, *k; i cant understand what m and *k stand for.
class B {
public:
virtual void msg() { cout << "classB"; }
};
class D: public B {
public:
virtual void msg() { cout << "classD"; }
};
int main() {
B* p = new D, m, *k;
p->msg(); k = &m; k->msg();
. . .
}
Help, if you can explain how (and why so) this code will work.
thanks, for your time.
It declares multiple variables at once. This is basically the same as:
So
pis a pointer to an instance ofDallocated with new.mis a local instance of classBandkis a pointer toBthat is later assigned to point atm.The
msgfunction is called on both allocated objects via the pointerspandk.Note that
*applies to each variable declaration separately. SoB* a, b;doesn’t declare two pointers, but instead declares one pointer and one local object. This is the reason, that many people prefer to write the*directly in front of the variable name:B *a, bmakes this a bit more obvious.