Welcome! Log In Create A New Profile

Advanced

could someone explain this constructor to me, please

Posted by Anonymous User 
Announcements Last Post
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
Anonymous User
could someone explain this constructor to me, please
November 21, 2009 03:00PM
Language: C++
private: StrategyInterface * strategy_;   public: Context(StrategyInterface *strategy):strategy_(strategy) { }
I understand the part before the ':'. It says construct a Context with StrategyInterface *strategy as a parameter. What I don't get is "strategy_(strategy)".
avatar
Rey
Re: could someone explain this constructor to me, please
November 21, 2009 03:21PM
same as

strategy_ = strategy;

----
"Flying is learning how to throw yourself at the ground and miss." - Douglas Adams
"Time is a great teacher, but unfortunately it kills all its pupils ..." - Louis Hector Berlioz
I think animal testing is a terrible idea; they get all nervous and give the wrong answers.
Anonymous User
Re: could someone explain this constructor to me, please
November 21, 2009 03:28PM
I thought the ':' means "subclasses"

what is the purpose of appending "strategy_(strategy)" to the constructor?
avatar Re: could someone explain this constructor to me, please
November 22, 2009 12:48AM
@Rick

If I recreate your class in full:

Language: C++
class Context { public: Context(StrategyInterface *strategy);   private: StrategyInterface *_strategy; };   Context::Context(StrategyInterface *strategy) : _strategy(strategy){ /// <<<<< your question is about this line }


The syntax you're referring to is called the member initialisation list. This is a comma-separated list that can be used to initialise all the data members. The initialisation happens after any base classes have finished being constructed and before the code inside the constructor body is executed. It is optional for value types and pointers since you could have a bunch of assignment statements in the constructor body instead, but is mandatory for reference variables. References must be intact before the constructor body executes.

For classes that are derived from other classes, this is also the place that you forward any parameters to the base class' constructor. Note that the constructor of the base class must be first in the list (although some compilers tolerate any order) before any data members.
Anonymous User
Re: could someone explain this constructor to me, please
November 22, 2009 09:32AM
Thanks a lot Rob.
Sorry, only registered users may post in this forum.

Click here to login