Page 1 of 1

C++ Classes driving me crazy

Posted: Mon Apr 27, 2009 7:16 am
by tomhancocks
Need a bit of help with C++ classes.

What I'm wanting to do is to return a pointer of a newly allocated class so that I'm not having to lug an entire objects around my code. I need to do this via the constructor ideally.

I can do this in Objective-C, PHP and some others but I can't for the life of me figure this one out. I've checked tons of online tutorials/resources but they all either return an entire object or nothing??

Posted: Mon Apr 27, 2009 7:21 am
by Sylence

Code: Select all

MyClass* c = new MyClass();
return c;
Of course you have to delete the pointer when you no longer need it.

Posted: Mon Apr 27, 2009 7:22 am
by hybrid
Are you sure you want to do this in a constructor of a different class? Anyway, in that case you should give the constructor another parameter which is of type ptr* so you can pass it the pointer to your desired class (ptr in this case), instantiate the new class, and asssign it to the pointer inside the constructor. But, proper encapsulation looks different :wink:

Posted: Mon Apr 27, 2009 7:33 am
by tomhancocks
I've got this part, what I can't grasp is the creating of a constructor function inside the class.
for example in ObjC I would do something like this to create a constructor.

Code: Select all

@implementation MyObject

- (id)initWithName:(NSString *)aName {
    if (self = [super init]) {
        _name = [aName retain];
    }
    return self;
}

@end
which would return a pointer to the new object which I could pick up via a line somewhere else like so:

Code: Select all

MyObject *myObject = [[MyObject alloc] initWithName:@"Tom Hancocks"];
[myObject release];
Basically I'm used to the constructors always returning a pointer to themselves. C++ doesn't seem to do this.
Although I have a background in C, I'm rapidly discovering the C++ is very different to Objective-C.

edit: Have just tried Sylence's method. It works. Does this mean that C++ doesn't require initialisers/constructors in the same manor as Objective-C? If so, this is going to take some getting used to :?

Posted: Mon Apr 27, 2009 1:35 pm
by hybrid
Please try to read some tutorial on C++, otherwise it'll be far too much for a forum thread :wink:
What Sylence did is calling the default constructor on a dynamically allocated obkect of type MyClass. However, you can also statically allocate memory for the object and create the object without new: MyClass c;
This also calls the default constructor on the object c. If you want to give it a parameter, you'd have to call the constructor with an argument: MyClass c("name");
The same holds for the allocation with new. AFAIK that's very similar to what you have in your code. Just note that you have to clean up objects which you create with new. Statically allocated stuff is released by the system once the variable leaves scope.