Abruzzo Forte e Gentile
Abruzzo Forte e Gentile

Reputation: 14869

testing whether a function is virtual or is a constructor

I was reading Never Call Virtual Functions during Construction or Destruction by Scott Meyer about basic C++ usage.

I was wondering if g++ has some compiler flags to warn about this bad coding that is really effective. If not what could be a way to code to do this check?

If I would code such kind of check I would approach this job by using a stack and inserting a piece of information at each call (a way to implement a call stack.

What I still need is a way to test whether a function is a virtual or whether a function is a constructor: Is there anyway to do that that you know? Something similar to a .NET 'reflection' idea?

Upvotes: 2

Views: 317

Answers (2)

David Schwartz
David Schwartz

Reputation: 182829

PC-Lint will do it!

I ran it on this test program:

#include <stdio.h>

class Base
{
public:
        Base() { moo(); }
        virtual ~Base() { ; }
        virtual void moo(void) { printf("Base::moo\n"); }
};

class Derived : public Base
{
public:
        Derived() { ; }
        virtual void moo(void) { printf("Derived::moo\n"); }
};

int main(void)
{
        Derived j; // Outputs 'Base::moo'
}

And it complained:

Warning 1506: Call to virtual function 'Base::moo(void)' within a constructor or destructor

Upvotes: 2

johnsyweb
johnsyweb

Reputation: 141908

> cat nevercall.cpp             
class Transaction {
public:
    Transaction();
    virtual void logTransaction() const = 0;

    // ...
};

Transaction::Transaction()
{
    //...
    logTransaction();
}

class BuyTransaction: public Transaction {
public:
    virtual void logTransaction() const;

    //...
};

class SellTransaction: public Transaction {
public:
    virtual void logTransaction() const;

    // ...
};

int main()
{
    BuyTransaction b;
}

Using -Weffc++ warns about this if (and only if) virtual void Transaction::logTransaction() const is pure, as it is in Meyer's sample code:

> g++ -Weffc++ nevercall.cpp -o nevercall
nevercall.cpp:1:7: warning: 'class Transaction' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
nevercall.cpp: In constructor 'Transaction::Transaction()':
nevercall.cpp:12:20: warning: pure virtual 'virtual void Transaction::logTransaction() const' called from constructor [enabled by default]
nevercall.cpp: At global scope:
nevercall.cpp:15:7: warning: 'class BuyTransaction' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
nevercall.cpp:22:7: warning: 'class SellTransaction' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]

Upvotes: 2

Related Questions