Tuesday, December 23, 2008

Nirvana

Noooo...not "Come As You Are," Nirvana, but the calm state of being, peace of mind, Nirvana.

My bafflement in my last post, as to why the Objective-C doc said this,

Objective-C++ similarly strives to allow C++ class instances to serve as instance variables. This is possible as long as the C++ class in question (along with all of its superclasses) does not have any virtual member functions defined. If any virtual member functions are present, the C++ class may not serve as an Objective-C instance variable.

And, I was able to do this...

Class Foo
{
public:
Foo(){};

private:
virtual LookImAVirtualFunc(void){};
};


@interface Bar : NSObject
{
@private
Foo* foo;
}

Clearly Foo is a C++ class with a virtual function, and Bar is an Objective-C class with an instance to Foo, but the doc said. And, here's my gaff...the doc is *correct.* Objective-C class cannot have an instance to a C++ class that has virtual functions. However, an Objective-C class can have a *pointer* to a C++ class that has virtual functions. In my test I had a *pointer* and that is why it works.

If I had,

@interface Bar : NSObject
{
@private
Foo foo; // ERROR
}

which is the instance to the class. So, you can have a C++ class that has virtual functions as instance variables inside an Objective-C class, you just have to declare them as pointers.

Ahhh...serenity.



Thanks to Andre' Pang, Kai, and Uli Kusterer for answering my question on the obj-language@lists.apple.com.

No comments: