Solved

initializing pointer private member in C++

Posted on 2014-10-16
1
188 Views
Last Modified: 2014-10-22
class MyClass
{
public:
    MyClass( float f, char a );
private:
    float mFloat;
    char mCharacter;
    bool mBoolean;
    ClassA* mA;
};

MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ),mA(someobject)
{
}

Would it work if mA was initialized like this? Note: It is a pointer
0
Comment
Question by:LuckyLucks
1 Comment
 
LVL 31

Accepted Solution

by:
Zoppo earned 500 total points
ID: 40384361
Hi LuckyLucks,

yes, this works, pointers can be initialized this way where 'someobject' has to be a pointer too, the question is where you get the 'someobject' (which must be a pointer too) from.

You can either create a new pointer there or pass a pointer or reference to a ClassA in the constructor, i.e.:

MyClass( float f, char a )  : mFloat( f ), mBoolean( true ),mA( new classA )
{
}

MyClass( float f, char a, ClassA* ptrA )  : mFloat( f ), mBoolean( true ),mA( ptrA )
{
}

MyClass( float f, char a, ClassA& refA )  : mFloat( f ), mBoolean( true ),mA( &refA )
{
}

Note: The last one can even be used (and in fact is the only way) to initialize a member which is a reference instead of a pointer.

Hope that helps,

ZOPPO
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question