Aditya Sharma
Aditya Sharma

Reputation: 65

How to check if a function is actually defined or not in C++ class

I want to determine if a function definition actually exist in a class and call that function only if it exists (not just declared). Idea is function declaration will always be present in the class header file but it's implementation (function definition) may or may not be included in the compilation based on the some flags. Catch is that I can not use compiler flags in the source cpp files. Below is what I want to achieve:

class Base {
    public:
    void feature1(int x); // Definition always present
    void feature2(int y); // Definition always present
    void feature3(int z); // Definition may (or may not) be present in another cpp file / library 

};


int main(int argc, char *argv[]) {
    Base a1;

    if (a1.feature3 is available) {  // pseudo code 
        a1.feature3(5); 
    } else {
        printf("feature3 is not available\n");
    }

    return 0;
}

Can someone please help with a possible solution.

Upvotes: 0

Views: 440

Answers (2)

SeventhSon84
SeventhSon84

Reputation: 364

If one method is not defined (but only declare) and you try reference it, linker won't be able to link. Maybe you could try a different approach to the problem (but depends on the requirements that you have), you could try using polymorphism like so:

class Base
{
  public:
     virtual void feature3(){throw NotImplementException()}
} 

class DerivedWithFeature3 : public Base
{
   public:
     void feature3(){/*do something*/}
}

int main(int argc, char *argv[]) {
    Base a1;

   try
   {
       a1.feature3(5);

   }catch(NotImplementException&)
   {
      printf("feature3 is not available\n");
    }

    return 0;
}

Upvotes: 2

james
james

Reputation: 889

The weak symbol should be able to do this for you:

class Base {
    ...
    ...
    void feature3(int z) __attribute__((weak));
}

int main(int argc, char *argv[]) {
    Base a1;

    if (a1.feature3) { 
        a1.feature3(5); 
    } else {
        printf("feature3 is not available\n");
    }
    return 0;
}

Upvotes: 1

Related Questions