c++ : Crash Saying "Pure virtual called" - visual-c++

{ using Visual Studio 2010 , Win7 }
class Base
{
public:
Base() : terminateCondition(false)
{
//spawn new thread and set entry point to newThreadFunc()
}
virtual ~Base() // edited to say it's virtual.
{
terminateCondition=true;
//wait for thread to join
}
virtual void vfunc() = 0;
static void __stdcall newThreadFunc(void *args)
{
while(!terminateCondition)
pThis->vfunc();
}
volatile bool terminateCondition;
};
class Derived : public Base
{
public:
virtual void vfunc()
{
//Do Something
}
};
Derived* dPtr=new Derived; //now assume pThis is dptr
//later somewhere
delete dPtr;
This code crashes saying pure virtual called. Moving terminateCondition=true to the destructor of Derived prevents this crash. I think i partially get why. Destruction is in reverse order of construction so d'tor of Derived is executed 1st and all functionalities of Derived are destroyed before calling upon the d'tor of Base. In the meantime if pThis->vfunc() is encountered the application would crash. It crashes saying pure virtual called. I could not understand this part. Can someone please explain?

Your Base class destructor needs to be virtual, Since it is not this code invokes Undefined Behavior.
Reference:
C++03 standard: Section 5.3.5/3:
If the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
When you call a virtual function through constructor/destructor the dynamic dispatch does not work as you expect it to.
The type of this in constructor/destructor is of the type of the class who's constructor/destructor is being executed. While you expect the dynamic dispatch to call overidden derived class method Derived::vfunc(), it ends up in a call to Base::vfunc() which does not have a definition and hence results in Undefined Behavior.
Reference:
C++03 Standard 10.4/6:
"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."

This happens because in your code vfunc can be invoked while Base::Base() isn't finished yet or Base::~Base() already started. Both of these cases will invoke undefined behavior, usually manifested as "pure virtual call" error.
Reason for it being an error is that the "virtual" mechanism doesn't kick in until after the constructor of most derived object's class started running, and the "virtual" mechanism is no longer in effect after the destructor of most derived object's class finished running. So when you make a call to a virtual function while a constructor or destructor is executing on the object, the corresponding function of the class of which the constructor or destructor is executing will be called. And if that function happens to be pure virtual, the behavior is undefined.
ISO/IEC 14882:2003, 10.4/6:
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making
a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or
destroyed) from such a constructor (or destructor) is undefined.

Related

why constructor is not called for static objects created inside a class?

#include<iostream>
class A
{
public:
int x;
A()
{
x=4;
std::cout<<"inside A constructor"<<std::endl;
}
void function()
{
std::cout<<"inside function"<<x<<std::endl;
}
};
class B
{
public:
B()
{
std::cout<<"inside b constructor"<<std::endl;
obj.function();
}
private:
static A obj;
};
B b;
A B::obj;
int main()
{
}
In the above code obj.function(); is called for the first time it knows that obj is a member of class A,since initialization of static objects done during the compile time itself,but why not the constructor is called.
The constructor is called only after control hits the line A B::obj;
if i declare the static A obj; outside class B then the constructor is called.
why the behavior is different for both?
B b;
when the above line executes,the constructor of B is called first.
so "inside b constructor" is printed first.
Then when control reaches obj.function(); the obj is already initialized by the
compiler since it is a static type of object.
so obj.function() is called without any problem and "inside function" is printed.
Now the control reaches A B::obj; definition of static object.
so constructor of A is called and "inside A constructor" is printed.
note:
only when the definition of static object is called the constructor is used.
so only we donot see constructor of A when static A obj; is declared inside the class B.
Another question may arise why declaration is only made for static variables inside a class and definition needs to be called explicitly outside class?
The answer is the definition of class can be made inside a header file and this header file can be included in multiple *.cpp files.
so,If the definition is also present inside the class then the static variable will have multiple definitions which will cause erroe.
Inorder to avoid the above the definition for static members outside a class is made exclusively.

Inheriting a base class from Modbus static library causes invalid stack pointer on return, but works fine when using base class directly

I'm using VC++2017 to write a program to communicate with a PLC using Modbus. Ideally, I want to create a class that inherits from the MbusAsciiMasterProtocol but it's looking like that will be impossible. My current header file for it is:
#pragma once
#include "MbusAsciiMasterProtocol.hpp"
class PlcModbus
: public MbusAsciiMasterProtocol {
public:
/* Also tried without calling MbusAscii constructor and doesn't work*/
PlcModbus() : MbusAsciiMasterProtocol() {}
~PlcModbus() {}
};
and the part in the main function that uses it is
/* Doesn't work */
int dataArr[18];
PlcModbus plc;
plc.openProtocol("COM3", 19700L, 8, 1, 0);
plc.readMultipleLongInts(1, 1, dataArr, sizeof(dataArr) / sizeof(int)); // Breaks here
plc.closeProtocol();
Which throws a null pointer exception when it gets to plc.readMultipleLongInts (it successfully calls openProtocol and opens the connection). I did some digging with the debugger and found that the stack pointer after the function is called is 12 spaces away from where it was prior to the function call.
Now, if I don't inherit from MbusAsciiMasterProtocol and instead use the class directly, everything works fine.
/* Works fine */
int dataArr[18];
MbusAsciiMasterProtocol plc;
plc.openProtocol("COM3", 19700L, 8, 1, 0);
plc.readMultipleLongInts(1, 1, dataArr, sizeof(dataArr) / sizeof(int));
plc.closeProtocol();
There is no runtime error and I am able to communicate with the PLC. This makes absolutely no sense to me because up until this point I assumed that inheriting from a base class essentially gave you access to the same public and protected member functions within the base class. But this seems to imply otherwise.
I also tried to use MbusAsciiMasterProtocol as an object in PlcModbus and write wrappers around the functions I need, but that didn't work either and it gave the error "- The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."
#pragma once
#include "MbusAsciiMasterProtocol.hpp"
class PlcModbus {
public:
PlcModbus() : myModbus(MbusAsciiMasterProtocol()) {}
~PlcModbus() {}
int openProtocol(const TCHAR *portName, long baudRate, int dataBits, int stopBits, int parity) {
return myModbus.openProtocol(portName, baudRate, dataBits, stopBits, parity);
}
int readMultipleLongInts(int slaveAddr, int startRef, int *int32Arr, int refCount) {
return myModbus.readMultipleLongInts(slaveAddr, startRef, int32Arr, refCount);
}
void closeProtocol() {
myModbus.closeProtocol();
}
public:
MbusAsciiMasterProtocol &myModbus;
};
I feel there must be something going wrong with the calls to the static library based off of that error, but why it works when I use the base class and not when I inherit from it is beyond me. Any explanation about what's going on would be extremely helpful.
Cheers.
I don't know why inheriting from MbusAsciiMasterProtocol doesn't work for you.
However in your last code example where you write wrappers around functions you have one subtle error:
MbusAsciiMasterProtocol &myModbus; creates a reference to MbusAsciiMasterProtocol object.
In the constructor you are initializing it with MbusAsciiMasterProtocol() - a temporary object thus creating a reference to a temporary. This is probably the source of the errors you are getting. Remove the reference and make the object private instead of public.

does dispose method disposes the calling object also?

I found the following code on MSDN:
public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;
public MyResource(IntPtr handle)
{
this.handle = handle;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
CloseHandle(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource()
//obj.dispose()
}
}
Now the confusion I have here is that, if I call obj.dispose, it disposes the objects created in the class MyResources i.e. handle, component etc. But does the obj also gets removed off the heap?? Same applies with the destructor. If I don't call dispose, the destructor will be called sometime. The code inside destructor removes the contained objects. But what about the obj?
Secondly, if I don't have a destructor defined inside the class and I dont even call dispose, does the GC never come into picture here?
IDisposable exists to remove unmanaged items from your managed objects. The runtime automatically provides a destructor, this destructor here has the sole purpose of releasing unmanaged items. As soon as your object goes out of scope or is set to null and has no more references to it will eventually be cleared by the GC.
The fundamental rule I'd recommend with with IDisposable is that at any given moment in time, for every object that implements IDisposable, there should be exactly one entity which has the clearly-defined responsibility of ensuring that it will get cleaned up (almost always by calling Dispose) before it is abandoned. Such responsibility will initially belong to whatever entity calls the IDidposable object's constructor, but that entity may hand the responsibility off to some other entity (which may hand it off again, etc.).
In general, I'd guess that most programmers would be best served if they pretended finalizers and destructors did not exist. They are generally only needed as a consequence of poorly-written code, and in most cases the effort one would have to spend writing a 100%-correct finalizer/destructor and working through all the tricky issues related to threading context, accidental resurrection, etc. could be better spent ensuring that the primary rule given above is always followed. Because of some unfortunate design decisions in the Framework and its languages, there are a few situations which can't very well be handled without finalizers/destructors, but for the most part they serve to turn code which would fail relatively quickly into code which will mostly work but may sometimes fail in ways that are almost impossible to debug.

non-static variable this cannot be referenced from a static context

I'm working with java me. I tried to switch to a displayable(form2) in Second.java from an okCommand in another displayble(form1) in First.java (see my previous question on that).
I got an error non-static method getForm2() cannot be referenced from a static context. I had to add the word static to form2 declaration and also at the getForm2 method in Second.java before it could work.
Problem now is that a backCommand in form2 can't switch back to form1 in First.java and it pops up the error non-static variable this cannot be referenced from a static context.
I paused and took some time to refresh myself on the language fundamentals on how the static keyword is used and I got to know that a static method is a class method and a non-static method is an instance method and that a non-static cannot call a static method unless an instance of the non-static method is created and also that a static method can't call a non-static method.
I'm really not understanding the implementation as I should, and I'd appreciate some clarification using my example above.
Here's the source below from Second.java the error is coming from form2.setCommandListener(this);
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(this);
}
return form2;
You have a static method, but are using this. But this doesn't exist. It would normally reference to an instance of the class, but you don't have one here.
If your method wasn't static and you instantiated an instance of this class then this would work.
e.g.
Second s = new Second();
Form f = s.getForm2(); // if this method wasn't static
Making that method static means little more than namespacing. There isn't an associated instance and no this.
There are couple options. First is to create a static instance of Second and use it in the getForm2:
//...
// static instance
private static Second instance = new Second(/* put constructor arguments here, if any */);
//...
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(instance); // --> replace "this" with "instance"
}
//...
From the issues you describe though, I would prefer another option - returning to design you had in previous question and use an instance of Second as an argument passed via constructor of First.
Your First.java would then have lines like:
//...
private final Second second; // instance needed for commandAction
//...
First(Second second) { // constructor with parameter
this.second = second; // save the parameter
//...
}
Then, commandAction method in First.java could use code like:
switchDisplayable(null, second.getSecondForm());
// instead of Second.getSecondForm()

Why won't the GC automatically dispose my class's members?

When I build the following C++/CLI code in VS2008, a code analysis warning CA1001 is displayed.
ref class A
{
public:
A() { m_hwnd = new HWND; }
~A() { this->!A(); }
protected:
!A() { delete m_hwnd; }
HWND* m_hwnd;
};
ref class B
{
public:
B() { m_a = gcnew A(); }
protected:
A^ m_a;
};
warning: CA1001 : Microsoft.Design :
Implement IDisposable on 'B' because
it creates members of the following
IDisposable types: 'A'.
To resolve this warning, I would have to add this code to class B:
~B() { delete m_a; }
But I don't understand why. Class A implements IDisposable via its destructor (and finalizer).
So surely whenever A gets garbage-collected, then A's finalizer or destructor will get called, freeing its unmanaged resources.
Why does B have to add a destructor to call 'delete' on its A member?
Will the GC only call A's destructor if B explicitly calls "delete m_a"?
Edit: it seems this works automatically if you use the "syntax sugar" method of declaring the A member, like this:
ref class B
{
public:
B() { }
protected:
A m_a;
};
but this is not always possible.
Why isn't the GC clever enough to automatically dispose of the managed reference pointer of A^, once no one else has a pointer to it?
You should use stack semantics for the member and add a destructor to the containing class.
Then the member will be disposed.
See http://msdn.microsoft.com/en-us/library/ms177197.aspx
ref class B
{
public:
B() {}
~B() {}
protected:
A m_a;
};
The member is still a ref. type and is still created on the heap.
Edit:
Dispose in .net is at best unfortunate, in C# the whole deterministic behaviour is broken and you have to be really rigerous with Dispose calls to get the behaviour most c++ developers expect.
In c++/cli stack semantics make it better. If you can't use them you are back to having to explicitly call dispose which in c++/cli is represented by the destructor.
The only way to automatically chain dispose calls to members is through stack semantics if the members are normal managed pointers just like c# you'll have to chain the calls manually.
Many classes could hold the same A^ pointer, there is no way to know which one should call the destructor.
You get the warning because you have implemented the destructor which causes your class to implement IDispose. This gives you a chance to clean up in a deterministic manner.
The GC alone can only collect an object with no references and call the finalizer. This is far from deterministic. Note that relying on the finalizer to do the clean up should be a safety net only as it may be called a long time in the future if at all.
I would recommend trying to design your code to allow the above pattern.

Resources