Solved

initializing pointer private member in C++

Posted on 2014-10-16
1
182 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 30

Accepted Solution

by:
Zoppo earned 500 total points
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now