Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a compiler warning/error when object sliced

I want to know if it is possible to let compiler issue a warning/error for code as following:

Note:

1. Yea, it is bad programming style and we should avoid such cases - but we are dealing with legacy code and hope compiler can help identify such cases for us.)

2. I prefer a compiler option (VC++) to disable or enable object slicing, if there is any.

class Base{};
class Derived: public Base{};

void Func(Base)
{

}

//void Func(Derived)
//{
//
//}

//main
Func(Derived());

Here if I comment out the second function, the first function would be called - and the compiler (both VC++ and Gcc) feels comfortable with that.

Is it C++ standard? and can I ask compiler (VC++) to give me a warning when met such code?

Thanks so much!!!

Edit:

Thanks all so much for your help!

I can't find a compiler option to give a error/warning - I even posted this in MSDN forum for VC++ compiler consultant with no answer. So I am afraid neither gcc nor vc++ implemented this feature.

So add constructor which take derived classes as paramter would be the best solution for now.

Edit

I have submit a feedbak to MS and hope they will fix it soon:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=421579

-Baiyan

like image 826
Baiyan Huang Avatar asked Feb 24 '09 03:02

Baiyan Huang


People also ask

What is a warning message generated by a compiler?

Compiler warnings are messages produced by a compiler regarding program code fragments to be considered by the developer, as they may contain errors. Unlike compilation errors, warnings don't interrupt the compilation process.

Is warning an error in C?

In the C Programming Language, the #warning directive is similar to an #error directive, but does not result in the cancellation of preprocessing.


1 Answers

If you can modify the base class you could do something like:

class Base
{
public:
// not implemented will cause a link error
    Base(const Derived &d);
    const Base &operator=(const Derived &rhs);
};

Depending on your compiler that should get you the translation unit, and maybe the function where the slicing is happening.

like image 163
Andrew Khosravian Avatar answered Sep 21 '22 04:09

Andrew Khosravian