-1

With regards to this piece of code:

#include <iostream>

class CClass1
{
public:
    void print() {
        std::cout << "This should print first" << std::endl;
    }
};

class CClass2
{
public:
    void print() {
        std::cout << "This should print second" << std::endl;
    }
};

So someone asked an interesting question about having a "free pointer" (so to speak) which can point to multiple instances of different objects without having to create a new type of that object. The person had the idea that this pointer can be of type void * and since it is void, it can be made to point to any instance of an object and access the object's public properties.

The following solution was submitted:

int main() {
    void *pClass(NULL);
    ((CClass1 *)(pClass))->print();
    ((CClass2 *)(pClass))->print();
    std::cin.ignore();
    return 0;
}

My question is why does the above work, but this doesn't:

int main() {
    (CClass1 *FG)->print();
    (CClass2 *FG)->print();
    std::cin.ignore();
    return 0;
}
smac89
  • 39,374
  • 15
  • 132
  • 179
  • The first one doesn't work, either. It's not pointing to a proper object. – chris Aug 24 '13 at 01:33
  • It compiled fine for me, which is why I started experimenting @chris that is exactly why I was amazed it worked because there is no real object to point to but it still printed the correct things – smac89 Aug 24 '13 at 01:34
  • You'll come to love that compiling it is only half the battle, generally the easy half. – chris Aug 24 '13 at 01:35
  • @chris it also executed i.e. it printed the correct output for each time the class was called. Compiler I use: gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1) – smac89 Aug 24 '13 at 01:38
  • But it's still ultimately undefined behaviour, and appearing to work is just one of the ways it can screw you over (probably the worst). – chris Aug 24 '13 at 01:46
  • Yep, it causes a seg fault when I add variables to the class then try to print the variables the same way. Thanks for your input – smac89 Aug 24 '13 at 01:48

1 Answers1

1

Your first example exhibits undefined behavior, by calling a non-static member function via a pointer that doesn't point to a valid object. It only appears to work by accident, because the function in question just happens not to use this in any way.

Your second example is, quite simply, syntactically incorrect. I'm not even sure what you are trying to do there; the code makes no sense.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • I was trying to replicate what the first code was doing. It wasn't pointing to a valid object which is why I thought I should try the second code and see what happens. – smac89 Aug 24 '13 at 01:49