c++ - Multiple classes with the same name causing vtable problems -


i have interesting problem crept , wondering why gcc/g++ doesn't catch , throw kind of error.

apologies how many files takes, i've reduced problem as possible.

interface.h

class baseclass { public:     virtual void hello() = 0; };  void rememberclass(baseclass* foo); void callfunc(); 

interface.c

#include "interface.h"  namespace {   typedef void (baseclass::*memfunptr)();   memfunptr func;   baseclass* obj; }  void rememberclass(baseclass* foo) {     func = &baseclass::hello;     obj = foo; }  void callfunc() {   (obj->*func)(); } 

class1.h

class class1 { public:   class1(); }; 

class2.h

class class2 { public:   class2(); }; 

class1.c

#include "interface.h" #include "class1.h" #include <iostream>  class helloclass : public baseclass { public:   helloclass() {}   void hello() {     std::cout << "calling hello" << std::endl;   } };  class1::class1() {   helloclass* foo = new helloclass();   rememberclass(foo); } 

class2.c

#include "interface.h" #include "class2.h" #include <iostream>  class helloclass : public baseclass { public:   helloclass() {}   void hello() {     std::cout << "calling hello 2" << std::endl;   } };  class2::class2() {   helloclass* foo = new helloclass();   rememberclass(foo); } 

main.c

#include "class2.h" #include "interface.h" int main(int argc, char** argv) {   class2 a;   callfunc(); } 

output

g++ class1.c interface.c main.c class2.c ./a.out calling hello 

as can see above, though constructing class2, prints output class1. because vtable helloclass in both class1 , class2 have same address helloclass::hello(), , address of function in class1.c

i'm assuming because when gcc doing linking, sees vtables classes same mangled names , discards 1 of them. should warn this? or cause error. have tried -wall , -wextra nothing mentioned.

no, standard explicitly allows compiler silently wrong thing in case.

explicitly, causing undefined behavior having 2 conflicting definitions same decorated name in same program.

it called odr "one definiton rule".

chapter 3.2.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -