Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

initializing pointer private member in C++

Posted on 2014-10-16
1
Medium Priority
?
199 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 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

877 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