How do you clone() in linux inside a class and namespace? - c++

I'm taking an intro to operating systems course and we're to use the clone() call in linux to create threads and then do some stuff with them. I seem to be having trouble just using clone() at all.
I've structured my code into a single class (called Homework) which is in the namespace for the class (Course). This may be the problem as this is the first time I've really used the namespace keyword. I'm trying to use the things I rarely do to become more experienced with it so if I have a dumb mistake, so be it.
I found some articles on the web but they didn't help much. I've read the man page but I guess I'm not experienced enough to understand what the problem is. One day! Thanks for any assistance :)
I want to have the method to catch the clones inside the class:
// -- Header -- //
namespace _Course_ {
class _Homework_ {
...
int threadCatch(void *);
...
};
}
// -- Source -- //
namespace _Course_ {
void _Homework_::threadTest(void) {
...
// From web article
void **childStack;
childStack = ( void **) malloc(KILOBYTE);
clone(threadCatch, childStack, CLONE_VM | CLONE_FILES, NULL);
...
}
int _Homework_::threadCatch(void * ){
cout << getpid() << " cloned." << endl;
exit(0);
}
}
Is what I currently have. I've tried different ways (taking the catcher out of the class, then namespace). It's compiled twice but when I try to recompiled after a make clean it tells me the function (threadCreate) is declared in multiple locations. Because of these weird errors I'm sure I'm doing something wrong and instead of hack at it I'll take some opinions. What should I do, or what should I read next? Thanks!

Define your catch function as a static class function.
static int threadCatch(void *);
Also (and you probably don't need this, but just in case, I'll say it here) you might also need to use the scope resolution operators to send it to clone(). I don't think so, since you're using it inside of the Homework class already. but I say it just in case, it might help you.
clone(Homework::threadCatch, childStack, CLONE_VM | CLONE_FILES, NULL);

The clone(2) system call expects a pointer to a function with C linkage. Since you're using C++ I'd recommend moving your threadCatch() function into the global namespace and declare it as an extern "C" function. You could also declare the method in your class as static but I feel that making it a free function with C linkage more closely matches how the function is to be passed as a parameter.
If you need to make calls to C++ objects inside your threadCatch() function that exist outside of it's scope you can pass pointers to those objects as the arg parameter to the clone() call. Your threadCatch() function would then cast the arg to the appropriate type so that you can access your C++ object(s) accordingly.

Related

Address of a method of an object in C++

As far as I know each created object has its own address, and each object's method also has its own address. I want to verify that with the following idea:
Step 1: Build class A with public method, its name is "method".
Step 2: Create two objects in class A, they are object "b" and object "c".
Step 3: Access the addresses of "b.method" and "c.method" to check that they are equal by using a function pointer.
But I met the problem in step 3 and have found every way to solve but failed.
So I posted up here to ask people to help me how to verify what I said above. Thanks everyone!
And here is my C++ code:
#include<iostream>
using namespace std;
class A
{
public:
int a;
void method()
{
//do something
}
static void (*fptr)();
};
int main()
{
A b, c;
A::fptr= &(b.method); //error: cannot convert 'A::method' from type
// 'void(A::)()' to type 'void (*)()'
cout << A::fptr << endl;
A::fptr= &(c.method); //error: cannot convert 'A::method' from type
//'void(A::)()' to type 'void (*)()'
cout << A::fptr << endl;
return 0;
}
Member functions are not like typical functions. The main difference is the way they are called (they have an implicit this argument), but that difference is enough for the language to demand a new way of defining pointers to them. See here for more details.
The following code prints the address in memory of a method:
#include <iostream>
class A {
public:
void method() {
}
};
int main() {
auto ptr = &A::method;
std::cout << reinterpret_cast<void*>(ptr) << "\n";
return 0;
}
As you can see, I had to cast the pointer to a void* to fool the compiler. G++ prints out a warning on that line, but otherwise does what you want with it.
Notice that the type of ptr is void (A::*)(), i.e. "a pointer to a method in A that receives no arguments and returns void". A pointer to methods in your B and C may be slightly different. They should convert to pointers to A, so you might want to go through that when comparing (or just cast to void* and ignore the warning).
Edited to add:
It seems no cast is needed for comparison. You can just directly compare the two pointers to methods, and they will return true or false correctly.
Thank you everyone!
I've been wondering about this for a long time, and now I've figured out the answer myself, there's only one "method()" that's created on memory, even if there are hundreds of objects created. All objects created that want to use this method will have to find the address of this method. Here is the code to prove what I said:
#include<iostream>
using namespace std;
class A
{
public:
int a;
void method()
{
//do something
}
static void (*fptr)();
};
int main()
{
A b,c;
if(&(b.method)==&(c.method))
{
cout<<"they are same\n";
}
else
{
cout<<"they are not same\n";
}
return 0;
}
The compiler and linker does not have to give distinct functions, distinct implementations.
On at least some platforms, the compiler will spot that 2 functions have the same implementation, and merge the 2 functions into a single piece of code. That limits the amount of bloat added by the template system, but stops it being a guaranteed behavior to identify different member functions.
The compiler can
inline all the examples of a single piece of code, and the result is it doesn't have an address.
share implementations where the code is the same.
create multiple implementations of the same function if it thinks it can be done faster.
When C++ was invented, there was a lot of effort to ensure that a C++ compilation unit was able to call a C compilation unit, and the result of this effort, was that many items of the C++ implementation became visible using compatibility tricks.
The C++ pointer to member function had no backwards-compatibility baggage, and thus no reason to allow it to be inspected. As such it is an opaque item, which can be implemented in multiple ways.
In your example there is only one copy of the method in memory. But i cannot think of any easy way to verify that. You can make thousands of objects and see the memory consumption. You can explore the memory occupied by your object in debugger. The memory consumption may be affected by operating system strategy for assigning memory to process. You can also explore disassembly at https://gcc.godbolt.org/
Relevant start for you would be https://godbolt.org/g/emRYQy

Passing function pointer with scope resolution operator arduino

I'm a newbie to arduino and programming.
I've included a library inside my own library in arduino, but first library contains a function which has a pointer function as a parameter. It is an interrupt service routine(ISR) but I need to call a function in my cpp file when interrupt is occurred. So I need to pass the pointer of that function to the first library code. It works well when I use it in .ino file, I can pass it like,
attachInterrupt(functionISR_name);
but when I use it in .cpp file, I get errors. my function is like,
void velocity::functionISR_name(){
//some code
}
but how can I pass the pointer of this function to the first library function? I tried this way but got errors,
attachInterrupt(velocity::functionISR_name);
You cannot pass a method to a function which expects a function, unless you define it static.
write it static :
static void velocity::functionISR_name()
and
attachInterrupt(&velocity::functionISR_name);
Unfortunately the static method is not bound to a specific instance any more. You should use it only together with a singleton. On Arduino you should write the class like shown below in the code snipped:
class velocity
{
static velocity *pThisSingelton;
public:
velocity()
{
pThisSingelton=this;
}
static void functionISR_name()
{
pThisSingelton->CallWhatEverMethodYouNeeded();
// Do whatever needed.
}
// … Your methods
};
velocity *velocity::pThisSingelton;
velocity YourOneAndOnlyInstanceOfThisClass;
void setup()
{
attachInterrupt(&velocity::functionISR_name);
// …other stuff…
}
This looks ugly, but in my opinion it is totally okay with Arduino as the opportunities are very limited on such a system.
Thinking again over it, I would personal go for the approach Sorin mentioned in his answer above. That would be more like that:
class velocity
{
public:
velocity()
{
}
static void functionISR_name()
{
// Do whatever needed.
}
// … Your methods
};
velocity YourOneAndOnlyInstanceOfThisClass;
void functionISR_name_delegation()
{
YourOneAndOnlyInstanceOfThisClass.functionISR_name();
}
void setup()
{
attachInterrupt(functionISR_name_delegation);
// …other stuff…
}
It would also save you some bytes for the pointer you need in the first example.
As a site note: For the future, please post the exact code (for e.g. attachInterrupt needs more parameter) and copy&paste the error messages. Usually error are exact at a place you do not suspect. This question was an exception. Normally I and other would ask for better specification.
You pass a pointer to the function but the function is a class member. Likely the call will be invalid because the this pointer will be garbage(may compile fine but will throw strange errors at runtime).
You need to define a plain vanilla function, outside of any class, and use that.
If you don't have a very complex project you can get away with having a global pointer to the class instance you should use and just delegate the call in your new function.
If you want to do thing the right way you need some mechanism to get the instance pointer I talked about above. Usually this involves either a singleton or some factory pattern.
Example:
class Foo {
void method() {
x = 5;
}
int x;
}
Having a callback on method will crash because you have an invalid pointer for this so x=5 will write 5 somewhere randomly in memory.
What you need is somehting like:
static Foo* foo_instance; // Initialized somewhere else.
void method_delegator() {
foo_instance->method();
}
Now you can pass method_delegator to the function. It will work because you now also pass foo_instance for this pointer.

Callback function pointers C++ with/without classes

I got stuck. I am trying to form a function that will eat classless function pointers and ones from objects. Here is my current code that hopefully explains more.
(It should run on a Arduino, so I cannot use big libraries.)
First off, I am using this library for the Arduino:
/* SimpleTimer - A timer library for Arduino.
* Author: mromani#ottotecnica.com
* Copyright (c) 2010 OTTOTECNICA Italy
*/
Which takes functions which it calls on a set timer interval of this type:
typedef void (*timer_callback)(void);
As far as my knowledge goes, it's a classles function, the webpage Pointers to member functions got me really far but, not far enough. Probably a terminology deficit on my side.
Now, I have made my own class which I would like in turn to use this SimpleTimer library. But if I feed the SimpleTimer my class functions, it does not like them (what I understand). But how would it be possible to make this happen without altering the SimpleTimer library.
So there is the class Robot, which has Robot::halt(). I want the robot to move forward for a set amount of time. Like so:
void Robot::forward(int speed, long time) {
reset();
timer.setTimer(time, c_func, 1);
analogWrite(l_a, speed);
analogWrite(r_a, speed);
isMoving(true);
}
void Robot::halt() {
__isMoving = false;
digitalWrite(r_a, LOW);
digitalWrite(r_b, LOW);
digitalWrite(l_b, LOW);
digitalWrite(l_a, LOW);
}
The c_func variable is a classless function at this point, but I would like to use the Robot::halt function. I have looked, read, learned but haven't succeeded yet. I just can't seem to wrap my head around this one because I am missing some angle.
I tried:
timer.setTimer(time, (this->*halt), 1);
timer.setTimer(time, Robot::*halt, 1);
timer.setTimer(time, &Robot::halt), 1);
But it would all amount to the same problem/ me just stabbing in the dark here...
EDIT
Earlier, I said not wanting to change the SimpleTimer library code. I want to comeback on this one, I guess altering it there would be the better option.
Thanks for all the current answers already, I was only allowed to flag one as a viable answer, actually everyhting I read here was extremely helpful.
To continue this, changing the SimpleTimer code. This class needs to have a reference to the object that holds my "halt" function, right? So, overloading the settimer function to something that takes my object and my function as two seperate pointers would work...? I think I am getting the hang of this but, I am not there yet with my head.
EDIT
I don't know who came with this one again but, anyone finding this thread. If found Member Function Pointers and the Fastest Possible C++ Delegates to give a very nice introduction in function pointers and member function pointers.
EDIT
Got it working, changed the SimpleTimer library to use this Delegate system:
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
It integrated very nicely, and it could be nice to have a standard Delegate system like this in the Arduino library.
Code as in test (working)
typedef
typedef FastDelegate0<> FuncDelegate;
Code in robot class:
void Robot::test(){
FuncDelegate f_delegate;
f_delegate = MakeDelegate(this, &Robot::halt);
timer.setTimerDelg(1, f_delegate, 1);
}
void Robot::halt() {
Serial.println("TEST");
}
Code in SimpleTimer class:
int SimpleTimer::setTimerDelg(long d, FuncDelegate f, int n){
f();
}
Arduino prints TEST in the console.
Next step putting it in an array, don't see a lot of problems there. Thanks everyone, I can't believe the stuff I learned in two days.
What's that smell? Is that the smell of...? Success!
For the ones interested, the used Delegate system does not amount to memory capacity issues:
With FastDelegate
AVR Memory Usage
----------------
Device: atmega2560
Program: 17178 bytes (6.6% Full)
(.text + .data + .bootloader)
Data: 1292 bytes (15.8% Full)
(.data + .bss + .noinit)
Finished building: sizedummy
Without FastDelegate:
AVR Memory Usage
----------------
Device: atmega2560
Program: 17030 bytes (6.5% Full)
(.text + .data + .bootloader)
Data: 1292 bytes (15.8% Full)
(.data + .bss + .noinit)
Finished building: sizedummy
You can do this by making a functor object, that acts as a proxy between the timer code and your code.
class MyHaltStruct
{
public:
MyHaltStruct(Robot &robot)
: m_robot(robot)
{ }
void operator()()
{ robot.halt(); }
private:
Robot &m_robot;
}
// ...
timer.setTimer(time, MyHaltStruct(*this), 1);
Edit
If it can't be done via a functor object, you could global variables and functions instead, maybe in a namespace:
namespace my_robot_halter
{
Robot *robot = 0;
void halt()
{
if (robot)
robot->halt();
}
}
// ...
my_robot_halter::robot = this;
timer.setTimer(time, my_robot_halter::halt, 1);
This only works if you have one robot instance though.
Since the timer callback signature doesn't take any argument, you unfortunately need to use some global (or static) state:
Robot *global_robot_for_timer;
void robot_halt_callback()
{
global_robot_for_timer->halt();
}
you can at least wrap that lot into it's own file, but it isn't pretty. As Matthew Murdoch suggested, it might be better to edit the SimpleTimer itself. A more conventional interface would be:
typedef void (*timer_callback)(void *);
SimpleTimer::setTimer(long time, timer_callback f, void *data);
void robot_halt_callback(void *data)
{
Robot *r = (Robot *)data;
r->halt();
}
ie, when you call setTimer, you provide an argument which is passed back to the callback.
The smallest change to SimpleTimer would be something like:
SimpleTimer.h
typedef void (*timer_function)(void *);
struct timer_callback {
timer_function func;
void *arg;
};
// ... every method taking a callback should look like this:
int SimpleTimer::setTimeout(long, timer_function, void *);
SimpleTimer.cpp
// ... callbacks is now an array of structures
callbacks[i] = {0};
// ... findFirstFreeSlot
if (callbacks[i].func == 0) {
// ... SimpleTimer::setTimer can take the timer_callback structure, but
// that means it's callers have to construct it ...
int SimpleTimer::setTimeout(long d, timer_function func, void *arg) {
timer_callback cb = {func, arg};
return setTimer(d, cb, RUN_ONCE);
}
You can't pass a non-static member function there - only a static one. The signature should be like this:
static void halt()
{
//implementation
}
the reason is that each non-static member function has an implicit Robot* parameter known as this pointer which facilitates access to the current object. Since the callback signature doesn't have such Robot* parameter you can't possibly pass a member function of class Robot unless it is static.
So that in your implementation
void halt();
is in effect
static void halt( Robot* thisPointer );
and when you do
void Robot::halt() {
__isMoving = false;
}
you effectively have this:
void Robot::halt( Robot* thisPointer ) {
thisPointer->__isMoving = false;
}
and of course a halt( Robot*) function pointer can't be passed in place of void (*)(void) C callback function.
And yes, if you need access to non-static member variables of class Robot from inside the callback you'll have to somehow retrieve the pointer to class Robot instance elsewhere - for example, store it as a static member variable so that you don't rely on this pointer.
It's important to understand that function pointers and pointers to class members are different not for an arbitrary reason but the fact that instance methods have an implicit this argument (also, they have to work with inherited and virtual functions, which adds even more complexity; hence they can be 16 or more bytes in size). In other words, a function pointer to a class member is only meaningful together with an instance of the class.
As the currently-top answer says, your best bet is to go with functors. While the setTimer function might only accept function pointers, it is possible to write a template function to wrap the call and accept both. For even more fine-grained processing, you can write a template metaprogram (Boost.TypeTraits has is_pointer, is_function and even is_member_function_pointer) to handle the different cases.
How you make the functors is a different story. You can opt for writing them by hand (which means implementing a class with operator() for each one of them), but depending on your needs that might be tedious. A couple of options:
std::bind: you can use it to create a functor whose first parameter will be bound to the value you specify - in the case of member functions, it will be the instance.
Depending on your compiler, you might not have access to std::bind - in this case I suggest boost::bind. It is a header-only library and provides the same functionality.
You can use another delegate implementation. I don't have experience with this one, but claims to be faster than other implementations (including std::function).
The mentioned libraries are header-only, so they probably don't count as "big libraries".

C++ getting rid of Singletons: alternative to functors and static methods

My noble quest is to get rid of singletons and static classes.
Background:
I have the following structures:
CmdFrequently instantiated object, it holds a name of the command (string), and functor to the static method of any class as a pointer.It is typically created in main classes such as Input, Console, Render, etc. and refers to methods within the class that it is created in, giving a runtime verbal interface to those methods.Cmds also interpret parameters in a form of a string array, where first argument is the name of the Cmd, and all consecutive strings are direct arguments for the static method being invoked. The argument count and argument array are stored in Commander, and changed before each Cmd call.
CommanderCommander is used to interpret string commands (which may come directly, or through Console) and it executes the Cmd which was stored in the buffer as a string (by invoking it's functor).
Problem:
Problem is that I am attempting to get rid of all the static classes (which I now turned into singletons for testing), and I am making the system fully modular and loosely coupled. This in turn prevents me from having static calls which Cmds could point to.
First instinct was to change the functor from a typedef into a template class, which would store an object and method, but it looks very messy and complex, and I personally am not comfortable going from:
Cmd::create("toggleconsole", Console::toggle);
To:
Cmd::create("toggleconsole", new FunctorObject<Console>(&Console::get(), &Console::toggle));
The final Cmd creation looks very obscure and misleading as to who is in charge of the Functor deallocation.
I am also in the process of moving Cmd creation from a static method call, into the Commander class, so it would look like commander.createCmd("command_name", ...); instead of Cmd::create("command_name",...); This is because Commander is no longer going to be static (or singleton), so all commands which it handles must belong to it.
I am, however, at a complete loss as to what my options/alternatives are to register Cmds, and maintain the loose coupling by allowing string commands to be issued to the Commander.
I have considered making each of the main classes derive from a CmdListener class, which would register the object with the Commander upon creation, and then during execution pass a command to all registered objects which overwrote the "onCmd(const Cmd &command)".
This leaves some unanswered questions as well: how will Cmd relay which method of class should be invoked? Keeping pointers wouldn't make sense and would be subject to high level of obscurity (as demonstrated above). Also, I wish to not reinterpret strings in onCmd method for every class that may handle that cmd.
It is a lot of information, but does anybody have any ideas on how to deal with this issue?
Also, all my classes must be aware of Commander and Console objects, which are no longer singleton/static. So far, I have placed them inside a Context object, and am passing it around like a little capsule. Any ideas on how to solve these post-singleton residual problems?
This project is my personal work, and I am planning to use it on my resume - hence, I do not want my potential employers to see any singletons (nor do I want to explain myself as to why, since I can prove to myself they are not truly necessary).
Thanks a ton!
edit: typography.
This is a job for the function class. You can find one in Boost, or in TR1 or C++0x. It looks like std::function<void()>, for example. This is often partnered with bind, which you will need if you want to refer to functional objects in a generic way, rather than take them by value, and is also found in Boost, TR1 or C++0x. If you have lambda functions, you can use them too, which is an excellent method.
class Commander {
std::map<std::string, std::function<void()>> commands;
public:
void RegisterCommand(std::string name, std::function<void()> cmd) {
commands[name] = cmd;
}
void CallCommand(std::string name) {
commands[name]();
}
};
void sampleFunc() {
std::cout << "sampleFunc()" << std::endl;
}
struct sampleStruct {
int i;
void operator()() {
std::cout << i;
std::cout << "sampleStruct()() and the value of i is " << i << std::endl;
}
};
int main() {
Commander c;
c.RegisterCommand("sampleFunc", sampleFunc);
sampleStruct instance;
instance.i = 5;
c.RegisterCommand("sampleStruct", instance);
std::string command;
while(std::cin >> command && command != "exit") {
c.CallCommand(command);
}
std::cin.get();
}

How a member func can know *programmatically* the 'name of the object' that is calling it?

Let say we have a class MyClass that has and a memberfunc().
An object is created for this MyClass, say ObjA.
i.e MyClass ObjA;
ObjA calls memberfunc().
Can we get this name 'ObjA' inside memberfunc() programatically?
Note: I know how to get the type of the object, i.e 'MyClass', using RTTI (Run-Time Type Identification), the same is also explained by radman below.
EDIT:
If this is NOT POSSIBLE in c++, Is it possible in any other programming language?
EDIT2
Made some modification to the question as few were unable to interpret.
There are several issues here:
Objects don't call anything, code does.
Objects don't have a name. An object is usually assigned to a variable, often to more than one variable, often to no variable at all, such as an array element.
Getting access to the call stack might give you some idea of the calling class that owns the code that called you, but even this usually requires a level of introspection that goes beyond the reflection facilities of most languages.
Python is a notable exception. It can give you the stack to walk and figure out lots of interesting things. C++ won't.
I have seen C++ libraries that crack open the stack (this is very non-portable, by the way) and thus give code the ability to figure stuff out like, "Who called me?" but I haven't used that stuff for years.
No, there is no way for it. C++ has no reflection, which would might make this possible. On 2nd thought, even the reflection facilities of e.g. Java don't have this feature.
C++ is compiled directly to machine code, which does not contain any identifiers from the source code anymore. You could of course store the "variable name" in a member field (provided the object is referred to under a single name...).
No, the object name is something that only exists in your source code. Once compiled, the object reference is just a memory offset. If you want to know the variable name, you have to have a string somewhere describing it.
The facility to get a variable name in languages with introspection mechanisms (such as Reflection) is pretty limited and not at all widely available. Even in C# - the girly man language - to get a variable name you need to use a quirky C# 3.5 feature called projection and then jump through hoops to extract it. Even then, you have to program for it - it won't just be available at any point of the code.
After some thinking the question you are posing - getting the objects' name from a member function - is theoretically impossible. Consider this scenario:
class ObjA {
public:
void memberfunc() {
//confused??? instance1 or instance2?
}
};
//main
ObjA instance1;
ObjA* instance2 = &instance1;
instance2->memberfunc();
In the above example we have one instance of ObjA with two variables pointing to it(and I use term pointing rather loosely here). Those variables are something completely outside of any conceivable control of the object, hence it's impossible to get at them, even if the facility to get a variable name is available.
In C# you can use anonymous classes and Reflection to get a variable name. The method of doing so is quite awkward and if you are trying to use this to demonstrate something to someone, give up now, because you will both be confused. The technique uses some features that are new to mainstream programming and include anonymous classes, projection, extension methods and Reflection.
public static class Extensions {
public static string GetFirstPropertyName(this object obj) {
return obj.GetType().GetProperties()[0].Name;
}
}
public class Program {
public static void Main() {
int intVal = 5;
var name = (new {intVal}).GetFirstPropertyName();
//name=="intVal"
}
}
Well your question seems a little bit unclear but assuming that you want to print out the name of the class in one of it's member functions it is quite possible.
What you need to use is the typeid command. This extracts a close to human readable name for a an object of class type at runtime. However you can't rely on this name being consistent across platforms i.e. the name you get may vary from platform to platform (what I got from the example code below was '4ObjA'.
#include <iostream>
#include <typeinfo>
class ObjA
{
public:
void memberfunc()
{
std::cout << typeid(*this).name() << std::endl;
}
};
int main(int argc, char **argv)
{
ObjA obj;
obj.memberfunc();
}
Your question isn't entirely clear - do you want to know the object the method belongs to? Or the name of the method calling the member-function? Oo something else..?
In most object-oriented languages, you can get the name of the currently class quite easily:
class Myclass(object):
def memberfunc(self):
print self.__class__.__name__
obja = Myclass()
obja.memberfunc() # prints Myclass
You can't sensibly get the obja identifier as a name (in almost any language), and I can't see why you would want to (in cases like this, you'd use some kind of key/value mapping)
If you want to get the name of the method that called the method, you would have to inspect the call stack, e.g in Python using the inspect method:
import inspect
class Myclass(object):
def memberfunc(self):
current_call = inspect.stack()[0]
previous = inspect.stack()[1]
print previous[3]
def somefunc():
obja = Myclass()
obja.memberfunc() # prints somefunc
somefunc()
I imagine this isn't as easy in other languages
Again, the cases where you would want to do such a thing are rare, usually limited to introspection-heavy things like code coverage tools and debuggers
As has been covered in other posts, there is no direct way to access the variable name identifier that you choose in code at runtime - there is simply no need for it from the machine perspective. However, in Ruby it is trivial to get at the details of the caller in terms of its structure:
class Foo
def foo
puts self.class
end
end
class Bar < Foo
end
f = Foo.new
b = Bar.new
f.foo #=> Foo
b.foo #=> Bar
You can do similar in C++ with typeid, but it is not exact. For instance:
#include <iostream>
class Foo {
public:
void foo () { std::cout << typeid(this).name() << std::endl; }
};
int main () {
Foo f;
f.foo (); // on my system returns P3Foo
return 0;
}
This is sort of a hack, but you could use Macros to store the class identifier name. Here's what I mean:
#include <iostream>
#include <string>
#define createMyClass(x) MyClass x("x")
class MyClass{
string _name;
MyClass( const string& name ) : _name(name){}
memberfunc(){
std::cout << "Name: " << _name << std::endl;
}
}
int main (int argc, char **argv) {
createMyClass( ObjA );
ObjA.memberfunc(); // prints the name
return 0;
}