tags:

views:

101

answers:

2

Suppose in a method MA() of class A, a method MB() of class B is being called after creation of an object. Is there a way to know in MB() the name of the class and the method from which it is being called in C++ ??

+3  A: 

What you are talking about is a Stack Trace.

Stack Trace definition:

The stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown. It provides information on the execution history of the current thread, displaying the names of the classes and methods within those classes that had been called at the point when the exception occurred.

This SO question on "How can one grab a stack trace in C?" has the answer you need.

0A0D
+1 for this, but worth noting that C++ doesn't provide any features for or guarantees about the portable availability of stack inspection mechanisms
Tony
@Tony: Thanks for the clarification.
0A0D
And probably it work such simplistically only with builds which have symbol information. It would take lot more efforts if it is a release build without symbol information
Chubsdad
+1  A: 

A simpler and more generic way would be as follows:

a) Enable output tracing based on a run time condition (e.g. a particular environment variable) / debug switch

b) Log the entry and exit of each function along with thread id (to take care of multi threaded applications). For this use the __FILE__ and __LINE__ preprocessor directives.

c) Analyze the logs using a good logviewer application (e.g. DebugView on Windows)

Chubsdad