Pointer to an object that has a pointer member - c++

Are pointers to pointers legal in c++? I've come across this SO question: Pointer to Pointer to Pointer
But the answers aren't clear if it is legal c++ or not. Let's say I have:
class A{
public:
void foo(){
/* ect */
}
};
class B{
public:
A* a;
/* ect */
};
void Some_Func() {
B *b;
// besides this looking ugly, is it legal c++?
b->a->foo();
};
Is the line b->a->foo() OK to write? Is there a better way to represent this expression?

This is perfectly valid.But the term you are using "pointer to pointer" is wrong.
the term means a double pointer like **P,a pointer which holds the address of another pointer.
but your case is the pointer(of class A) is an member of a class whose pointer(of class B) is created by you in some_func

It is legal but in your example your program will crash (if you could compile it since your members are private) because you did not create an instance of B
void Some_Func() {
B *b; // uninitialized B ptr should be B* b = new B;
// legal
b->a->foo();
};
Although you may want to reconsider accessing variables directly as you do and instead have getter/setters to access private member variables.

Illegal, "a" is private. So is "foo".
If corrected to "public" then they're legal constructs.
From your code its hard to find a "better" way. BUT You can modify the code to make the code look much clearer:
class A{
public:
void foo(){ cout << "Work";}
};
class B{
private:
A *a;
public:
A& getA(){
return *a;
}
};
void SomeFunction()
{
B *b = new B();
B& bRef = *b;
bRef.getA().foo(); //better looking code?
delete b;
}

Yes but then you have to use pointer to pointer like **P.Actually if we want to access a pointer which is holding another pointer then we can do this.This is allowed in c++ but keep in mind that only in case if you have assigned a pointer to pointer p

Related

Casting pointer to different pointer causes wrong virtual function to be called

#include <iostream>
struct A {
virtual void a() {
puts("A");
}
};
struct B {
virtual void b() {
puts("B");
}
};
struct C {
virtual void c() {
puts("C");
}
};
struct D : public A, public B, public C {
virtual void c() {
C::c();
puts("cd");
}
};
int main() {
A* obj = new D;
obj->a();
B* b = (B*)obj;
b->b();
C* c = (C*)obj;
c->c();
return 0;
}
I have this code where I have non virtual multiple inheritance. However, it seems to call the wrong virtual function when I call the functions in the main function.
Instead of outputting:
A
B
C
cd
It outputs:
A
A
A
What puzzles me is that when I change the code to doing this:
B* b = (B*)(D*)obj;
b->b();
C* c = (C*)(D*)obj;
c->c();
It outputs what I would expect (see above). Afaik doing a double pointer cast like this wouldn't effect anything and would be optimized out by the compiler. But it seems to be changing what virtual function is being called.
Can someone explain why this would change what virtual function is being called?
Notes:
I printed the pointers at each step, they are the same.
I want to avoid using dynamic_cast (although it does work) as it's too slow for what I need it to do.
Can someone explain why this would change what virtual function is being called?
Generally, a C-style cast between pointer types won't change the value of the pointer and so will have no effect. There is, however, one exception.
A cast between a class and a parent or child class can change the value of the pointer. For example:
class A
{ int a; };
class B
{ int b; };
class C : public A, public B
...
Now, a pointer to an instance of class A will probably have the same value as a pointer to its a member and a pointer to an instance of class B will probably have the same value as a pointer to its b member. A pointer to an instance of class C can't have the same value as a pointer to both its A::a and its B::b members since they're distinct objects.
A function expecting a B* can be passed a C* since a C is a B. Similarly, a function expecting an A* can be passed a C* for the same reason. But at least one of these will require a value change to the pointer.
So casts between these types will change the values, the others are all no-ops.
Of course, all of this is UB. You are casting between unrelated types and then dereferencing them.
I want to avoid using dynamic_cast (although it does work) as it's too slow for what I need it to do.
That seems very hard to believe.

How to distinguish objects of derived classes C++

Look at following code:
class A
{
protected:
int aa = 1;
};
class B : public A
{
private:
int bb = 2;
public:
int getbb() { return bb; }
};
class C : public A
{
private:
int cc = 3;
public:
int getcc() { return cc; }
};
int main()
{
std::vector<A> a;
B b;
C c;
a.push_back(b);
a.push_back(c);
a[0].getbb(); //getbb() unaccessible;
a[1].getcc(); //getcc() unaccessible;
}
A is the based class. B and C is the derived classes. I want to set a vector to hold either B or C, and use vector a to hold A. However, since a is a vector containing A's objects, I can't access methods in B and C. Is there anyway to make a[0].getbb() and a[1].getcc() work?
Your vector of A is not capable of holding Bs or Cs, because it stores A by value, resulting in object slicing when B or C is stored. In particular, this means that when you store B, only aa gets stored; bb gets sliced away.
In order to store subclasses without slicing use a container of pointers - preferably, of smart pointers.
This wouldn't help you access functionality specific to B or C without a cast. One way to solve this problem is to give virtual member functions for B's and C's functionality to A, and make calls through A-typed reference of B or C.
Not without invoking undefined behaviour.
The problem is that a.push_back(b) and a.push_back(c) do not append objects b and c to the vector. They create instances of A that hold only the "A parts". This is called object slicing.
So there is no object of type B and no object of type C in the vector.
You force the issue and make your code compile by doing something like
static_cast<B &>(a[0]).getbb();
but this just has undefined behaviour, since it treats a[0] as being of type B when it is really of type A. Which makes it a really bad idea. Although it will (probably) compile, it could do anything - and probably not what you expect.
If your vector contains A * rather than A it is possible. For example;
int main()
{
std::vector<A *> a;
a.push_back(new B);
a.push_back(new C);
B* b = dynamic_cast<B *>(a[0]);
if (b) // if a[0] actually points at a B ....
b->getbb();
else
complain_bitterly();
C *c = dynamic_cast<C *>(a[1]);
if (c)
c->getcc();
else
complain_bitterly();
}
Of course, doing this has practical trap doors as well - such as requiring class A having at least one virtual member. It would be better off to work with a polymorphic base, and override virtual functions.
In other words, your design is broken, so fix it so it doesn't somehow require you to morph an object to a different type.
An alternative to using pointers is to use a vector of std::reference_wrappers and polymorphic classes. Small example below:
#include <functional> // for std::reference_wrapper
#include <iostream>
#include <vector>
class A
{
public:
virtual void printme()
{
std::cout << "A" << std::endl;
}
virtual ~A() = default;
};
class B: public A
{
public:
void printme() override
{
std::cout << "B" << std::endl;
}
};
class C: public A
{
public:
void printme() override
{
std::cout << "C" << std::endl;
}
};
int main()
{
std::vector<std::reference_wrapper<A>> a;
B b;
C c;
a.emplace_back(b);
a.emplace_back(c);
a[0].get().printme(); // need to "get()" the raw reference
a[1].get().printme();
}
Live on Coliru
According the the cpp reference, there seems to be a way to achieve this by using dynamic_cast. You first need to make your vector a vector of pointers to the base class A. Then when accessing any element, you can check if it is a B* (or a C*) by checking the result of the dynamic_cast operator.
From the CPP reference:
dynamic_cast < new_type > ( expression )
... If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type...
Accordingly, you can do this:
std::vector<A*> a;
B b;
C c;
a.push_back(&b);
a.push_back(&c);
...
int i = something;
B* pB = dynamic_cast<B*>(a[i]); if(pB != nullptr) pb->getbb();
C* pC = dynamic_cast<C*>(a[i]); if(pC != nullptr) pC->getcc();
p.s: It is highly questionable as design approach though. The recommended OOP approach would be certainly to use a virtual method in the base class A and override it in B and C. But (hopefully) this answers the exact question as stated in the title.
If you're sure they're instances of B and C, use cast:
static_cast<B>(a[0]).getbb();
static_cast<C>(a[1]).getcc();
OK, you may also create a vector of A*:
std::vector<A*> as;
as.push_back(new B);
as.push_back(new C);
B* b = (B*) as[0];
b->getbb();
c->getcc();
Now you only have to remember about freeing objects with delete.
You may use "Type IDs":
class A {
// ...
virtual int getTypeID() { return 0; }
}
class B {
// ...
virtual int getTypeID() { return 1; }
}
// analogically for C
It's virtual but is in prototype of A
Now use:
switch(a.getTypeID()) {
case 0:
// It's normal A
break;
case 1:
// It's B
// ...
break;
case 2:
// It's C
// ...
break;
}

Pointing a derived smart pointer to a stack object returned by base reference

I have a problem. I'd like to point shared_ptrs to objects that are stored in a class. In the code there is a Holder::getSomething() function that returns a reference to a base. I'd like to cast that to the derived b_ptr. Here's the code:
#include <memory>
using namespace std;
class A{
public:
int a;
A() : a(0){}
virtual ~A(){}
};
class B : public A {
public:
bool b;
B() : A(){ b = false; }
};
class Holder{
public:
B arr[1];
// there's an A ref here, not B, because i'll have a boatload of deriveds.
A& getSomething(){
return arr[0];
}
Holder(){
arr[0] = B();
}
};
int main(){
Holder h;
shared_ptr<B> b_ptr;
// b_ptr = something_alien_here(h.getSomething());
return 0;
};
I know ( and by "know" i mean i have an uneducated guess ) that i should use dynamic_(pointer_?)cast but i cant find/figure out the right syntax.
The whole point of a shared pointer is that its ref counted, and destructs
what it points to when the last one go out of scope. You don't want that to happen
to a member object of another class, since that is undefined behaviour.
in short; don't do that.
If you can guarantee that h will live longer than b_ptr, then you can use the borrowing constructor of shared_ptr, together with a cast:
Holder h;
std::shared_ptr<B> b_ptr(std::shared_ptr<B>(),
&static_cast<B&>(h.getSomething()));
Now b_ptr shares ownership with the temporary, empty shared pointer, which has the effect of never calling the deleter for B. This is why it is now your responsibility to guarantee that the pointee exists for at least as long as the shared pointer may be dereferenced.

polymorphic C++ references

I was wondering how you can do polymorphism with references, as opposed to pointers.
To clarify, see the following minimal example:
class A;
class B {
public:
A& a; ///////////////// <- #1
B();
void doStuff();
};
class A {
public:
virtual void doSmth() = 0;
};
void B::doStuff() {
a.doSmth();
}
class A1 : public A {
public:
void doSmth() {
}
};
B::B() : a(
* ////////////// <- #2
(new A1) /////////// <- #3
) {
}
This compiles and works, but as the most important point here is that a in line #1 is a reference, so in order to be able to use it polymorphically (is that an actual word?), as shown in line #3 I have to "convert a pointer to a reference" by dereferencing it.
This strikes me as a bit odd, and I was wondering if there is a better (in the sense of cleaner) way. Is it just me?
Rationale
It would be great if I didn't need a new at all, but when declaring (!) B I have no clue how to create an instance of A1 (!) as A is a forward declaration -- A1 is implemented in the same compilation unit as B. Still, is there a real need for dynamic memory allocation in this case? How would you do this?
Sorry for the slightly twofold question.
Edit
Note: B is huge (and I cannot make a template class of it), and will go out of scope precisely when the program terminates -- a is small and makes two big modules talk to each other, it will be needed as long as the instance of B lives (there is only one).
Edit 2
I just realised, that since both A and B are effectively singletons, I can simply create a static instance of A1 in the compilation unit of B, avoiding dynamic memory allocation (even if there were two Bs they could easily use the same instance of A). To be fair, I did not post this as answer, but will accept the answer that prompted me to come up with this solution.
There's nothing odd. Polymorphisms works both for pointers and references:
struct Base { };
struct Derived : Base;
void foo(Base &);
int main() {
Derived x;
foo(x); // fine
}
You're conflating this with another issue, namely creating a reference to a dynamic object:
T * pt = new T;
T & rt = *pt;
T & x = *new T; // same effect
Note that it's generally very bad style to track a dynamic object only by reference, because the only way to delete it is via delete &x;, and it's very hard to see that x needs cleaning up.
There are two immediate alternatives for your design: 1) make a a member object in B, or 2) make a a shared_ptr<A> or unique_ptr<A> and change the initalizer to a(new A1). It all depends on whether you actually need the polymorphic behaviour, i.e. if you have other constructors for B which assign a different derived class to a other than A1.
This is indeed a bit odd. If you want a member-variable of type A1 (rather than a reference), why not just rearrange your code so that the definition of A1 appears before the definition of B?
Still, is there a real need for dynamic memory allocation in this
case?
No. Just define A1 first and then make it a normal member of B.
Polymorphism works just fine with both references and pointers.
Erm, is this not sufficient?
#include <iostream>
struct A;
struct B
{
B(A& a);
void foo();
A& _a;
};
struct A
{
virtual void foo() =0;
};
struct A1 : public A
{
virtual void foo() { std::cout << "A1::foo" << std::endl; }
};
B::B(A& a) : _a(a) {}
void B::foo() { _a.foo(); }
int main(void)
{
A1 a; // instance of A1
B b(a); // construct B with it
b.foo();
}
Still, is there a real need for dynamic memory allocation in this case?
Either the dynamic memory allocation or injecting the reference into B's ctor.
It's no stretch to imagine why references can work polymorphically like pointers (not to mention references are often implemented as pointers anyway). Here's a quick example:
class Base {
public:
virtual void something() { }
};
class Derived : public Base {
public:
void something() { }
};
Base& foo() {
static Derived d;
return d;
}
foo().something(); // calls Derived's something
Also why are you allocating dynamic memory for a reference? You probably shouldn't be using a reference in this case at all. Also, writing classes with reference members effectively prevents assignment (as I heard someone say quite well).
I realize this is a really old post but there is another option you have for handling references for dynamically allocated objects. You can assign a reference to the dynamically allocated object. Below is some dummy code to give you an idea of how this works.
struct A
{
int b;
virtual void print();
A(int val):b(val) {}
};
struct A_child:public A
{
A_child(int val):A(val) {}
void print();
};
void A:print()
{
cout<<"parent\n";
}
void A_child:print()
{
cout<<"child\n";
}
struct test_ref
{
A *& ref;
test_ref(A * ptr) : ref(ptr)
}
int main()
{
test_ref parent(new A(12));
parent.ref->print();
test_ref child(new A_child(15));
child.ref->print();
}
To be honest I am not certain when this is a good idea. I just wanted to show an alternative approach where you dont have to dereference the dynamically allocated memory when initializing an object.
I am also pretty certain dynamically allocating a pointer while initializing a class where the pointer is stored as a reference pointer will probably lead to a memory leak unless you can delete the reference pointer.

How to call function from inherited class?

I have the code:
class A{ //base class
public:
virtual std::string getString(){return "class A";}
};
class B: public A{
public:
std::string getString() {return "it is B class";}
};
class C{
public:
C(){
B b;
a = b;
}
std::string test() {return a.getString();}
private:
A a;
};
int main()
{
C c;
std::cout << c.test();
return 0;
}
c.test() says "class A", but how I can call method getString() from class B and not A?
Thanks!
The problem is, your B object gets sliced when assigned to an A object. This is because you assigned by value, not by reference or pointer. Since you declared a like this
A a;
what happens during the assignment a = b is that the actual state of b is copied over into a. However, since a is a value object, only the A part of object b is copied, and its "B-ness" is completely lost!
To avoid this, you need to declare a as a pointer type, as suggested by others (a reference would also work, but then you would need to considerably rewrite your example, since you can't assign to references, only initialize them). If a is a pointer (A*), the assignment a = b makes a point to the object represented by b, which is still a B object, thus you will observe the polymorphic behaviour you expected. However, in this case, you must ensure that b stays alive even after exiting the constructor - otherwise you leave a dangling reference which causes undefined behaviour (read: bad things you don't want to happen) when dereferenced.
Since a pointer example was already shown by #Nawaz, I will give another using a reference:
class C{
public:
C() : a(b) { // references must be initialized in the constructor initializer list
}
std::string test() {return a.getString();}
private:
B b; // moved to class scope to ensure that it stays alive
A& a;
};
You need to implement like this:
class C{
public:
C(){
a = new B;
}
std::string test() {return a->getString();}
private:
A *a;
};
This will call getString() from class B and not A.
What you're trying to do is called "dynamic polymorphism" which is achieved through pointer (or reference) of type base class (which is A), but the pointer points to an object of type derived class (which is B).
Because your member a is not an A*, it is an A instance. Therefore you are just assigning the A part of B to variable a. if you convert a to an A*, you will get the expected result.
You are slicing therefore it will not work. a is an A it is not a B.
To work your class member variable a must be a pointer or a reference.
As a pointer
class C{
public:
C(){
a = new B;
}
std::string test() {return a->getString();}
private:
A *a;
};
As a reference
class C{
public:
C() : a( *(new B) )
{
}
std::string test() {return a.getString();}
private:
A &a;
};
Of course the code I have produced leaks but will work with the virtual function.