473,396 Members | 2,036 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

this in constructor

Is it unsafe to use 'this' in the constructor? Is there any book out there
(Stroustrup or Meyers or Sutter) that talks about this?

// small example - not compiled code
Test::Test(int a)
{
this->m_A = a; // I have seen this before
someClass->registerMe(this); // Is this okay also?
}
Thanks.
Jul 19 '05 #1
5 19506
WW
skscpp wrote:
Is it unsafe to use 'this' in the constructor?
No, it isn't. But you have to remember that (for example) reading
uninitialized members is an error.
Is there any book out
there (Stroustrup or Meyers or Sutter) that talks about this?
Uh. I don't recall.
// small example - not compiled code
Test::Test(int a)
{
this->m_A = a; // I have seen this before
This is surely OK, if m_A is indeed a member.
someClass->registerMe(this); // Is this okay also?


Well, it depends. If this is the last line (part) of your code in the
constructor (so your object is already fully constructed) it is OK. So if
you have failed to initialize a member, which is the accessed by registerMe
(or by something it calls(, that will indeed be a problem. But that can
also be done without "calling out" of the class/object:

struct Bang {
Bang() { incMe(); }
void incMe() {
++m_i;
}
private:
int m_i;
};

Since m_i is not initialized ++m_i; is undefined behavior.

--
WW aka Attila
Jul 19 '05 #2
skscpp wrote:
Is it unsafe to use 'this' in the constructor? Is there any book out there
(Stroustrup or Meyers or Sutter) that talks about this?

// small example - not compiled code
Test::Test(int a)
{
this->m_A = a; // I have seen this before
someClass->registerMe(this); // Is this okay also?
}


You'll have problems if someClass::registerMe() calls any
virtuals because the derived classes wont have been
constructed - the following will crash.

class A;
void somefunc(A* a);

class A {
public:
A() {
somefunc(this);
}
virtual void vfunc() = 0;
};

class B : public A {
public:
B() {}
virtual void vfunc() {};
};

int main()
{
B b;
return 0;
}

void somefunc(A* a)
{
a->vfunc();
}
Jul 19 '05 #3
When you are initializing member variables in a constructor, you
are implicitly using "this". It is safe to use it.

See the following article for the mapping of contstructor code
to C. This should clarify the role of "this".

http://www.eventhelix.com/RealtimeMa...erformance.htm

Sandeep
--
http://www.EventHelix.com/EventStudio
EventStudio 2.0 - Generate Sequence Diagrams and Use Cases in PDF
Jul 19 '05 #4

"skscpp" <sk*****@hotmail.com> wrote in message news:bm**********@news.lsil.com...
Is it unsafe to use 'this' in the constructor? Is there any book out there
(Stroustrup or Meyers or Sutter) that talks about this?


It's not unsafe as long as you are cognizant of what parts of the current
object have already been constructed. In this case, you are using this
to set an initial value which would appear to be OK (I assume m_A is an
int member of Test).

Of course:
this->m_A = a;
in that case is the same as
m_A = a;

Even then, it would be better to INITIALIZE m_A rather than assigning to
it afterwards:

Test::Test(int a) : m_A(a) {
someClass->registerMe(this);
}

As for the call to registerMe, it should be noted that Test (or whatever object
that Test is a base class for), is not yet fully constructed. If all it does is
remember the pointer and not use it until after the constructors finish, then
all is OK again.
Jul 19 '05 #5
ev********@yahoo.com (Sandeep) wrote in message news:<90**************************@posting.google. com>...
When you are initializing member variables in a constructor, you
are implicitly using "this". It is safe to use it.

See the following article for the mapping of contstructor code
to C. This should clarify the role of "this".

http://www.eventhelix.com/RealtimeMa...erformance.htm

Sandeep

But in the original post, "this" is being used for more than
initializing member variables.

someClass->registerMe(this);

Who knows what this function actually does. It could be calling
this->( some virtual function ). In this case, there would be
problems.

-Brian
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Vinodh Kumar | last post by:
class A { int myIntVal; }; int main() { A a; return 0; }
15
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including...
4
by: Kench | last post by:
Sorry if this becomes a repost. I posted this to comp.lang.c++.moderated 1 hour ago still it does not show up there so posting this here. Hi, Consider class A & B both of which implement a copy...
3
by: ccs | last post by:
In Meyers' book he gave an example of "virtual copy constructor", which is quite different to an "ordinary" copy constructor by: 1. it returns a pointer to an object instead of a reference. 2. it...
17
by: highli | last post by:
When a non-default constructor provided in a class, the default constructor is not available anymore. In what cases shall a default constructor be defined explicitly? Specifically, in the...
2
by: vakap | last post by:
function show() { var s = '' ; for (var i = 0; i<arguments.length; s += '\n'+arguments) ; typeof(window) != 'undefined' ? window.alert(s) : WScript.Echo(s) ; } function f(){}...
7
by: ad | last post by:
When a class (say class1) inherited form another class (Class0). The constructor in the class0 will be executing before the constructor of class1. Can we over the constructor?
4
by: TJS | last post by:
How can I override the default values, of a class constructor , from an ASP.net page ? Public Sub New( ) HeaderStyle.BackColor = ColorTranslator.FromHtml("#5C85AD") HeaderStyle.ForeColor =...
8
by: shuisheng | last post by:
Dear All, I am wondering how the default copy constructor of a derived class looks like. Does it look like class B : public A { B(const B& right) : A(right) {}
4
by: Rahul | last post by:
Hi Everyone, It is well known that the input parameter which is passed to the copy constructor is passed as reference and not as as object. Because passing an object is as good as making another...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.