473,783 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling one constructor from another in VC++

I'm fairly new to C++ and VC++, but for the most part it seems to do most of
the same things that can be done in Java, with just some syntactic and
structural adjustments. However, one thing I haven't been able to figure out
is how to call one constructor from another within a class. It's easy enough
to call the base class's constructor from the derived class, but that's not
what I'm trying to do.

For example, in Java (or J#) it's easy to do this:

public class Circle
{
private int PointX;
private int PointY;
private int Radius;

public Circle()
{
this.PointX = 0;
this.PointY = 0;
this.Radius = 0;
}

public Circle(int x, int y)
{
this();
this.PointX = x;
this.PointY = y;
}

public Circle(int x, int y, int r)
{
this(x, y);
this.Radius = r;
}
}

However, trying to do the same thing in VC++ doesn't work:

// Sphere.h (partial file)
class Sphere
{
public:
Sphere(void);
Sphere(int x, int y);
Sphere(int x, int y, int r);
~Sphere(void);

private:
int PointX;
int PointY;
int Radius;
};

// Circle.cpp (partial file)
#include ".\circle.h "

Circle::Circle( void)
{
this->PointX = 0;
this->PointY = 0;
this->Radius = 0;
}

Circle::Circle( int x, int y)
{
Circle();
this->PointX = x;
this->PointY = y;
}

Circle::Circle( int x, int y, int r)
{
Circle(x, y);
this->Radius = r;
}

In the C++ version, I also tried using this() instead of Circle(), which
caused a compiler error. I also tried doing it without the this-> specifier,
which made no difference. The end result if you call the second constructor
is that the X and Y values have been set, and the Radius is uninitialized.
If you use the third constructor, you get exactly the opposite results. (And
I don't mean they have values of zero; looking at them with the debugger, I
see values of -842150451 for the uninitialized members.)

So is there any way in C++ to let one constructor build on another like
this?

Thanks for any help.
Nov 17 '05 #1
31 5195
Peter E. Granger wrote:
I'm fairly new to C++ and VC++, but for the most part it seems to do
most of the same things that can be done in Java, with just some
syntactic and structural adjustments.
Actually, there are many things you can do in C++ that have no counterpart
in Java at all. You'll discover them in time.
However, one thing I haven't
been able to figure out is how to call one constructor from another
within a class. It's easy enough to call the base class's constructor
from the derived class, but that's not what I'm trying to do.


There's no way to do this in C++. Unlike Java, in C++ at the start of the
first statement of a constructor's body all of the members have been
initialized (their constructors have been run if they have them). In Java
everything gets default initialized before the constructor body is run, and
then the constructor body (perhaps redundantly) initializes everything.

To get the same "constructo r re-use" effect in C++, you have to put the
initialization code into a (private/protected) member function and call it
from the constructor(s).

-cd
Nov 17 '05 #2
Peter E. Granger wrote:
I'm fairly new to C++ and VC++, but for the most part it seems to do most of
the same things that can be done in Java, with just some syntactic and
structural adjustments. However, one thing I haven't been able to figure out
is how to call one constructor from another within a class. It's easy enough
to call the base class's constructor from the derived class, but that's not
what I'm trying to do.
<snip>
Circle::Circle (int x, int y)
{
Circle();
The statement above creates a temporary Circle object, which is immediately
destroyed at the end of the statement.
this->PointX = x;
this->PointY = y;
}

Circle::Circle (int x, int y, int r)
{
Circle(x, y);
The statement above creates a temporary Circle object, which is immediately
destroyed at the end of the statement.
this->Radius = r;
}

In the C++ version, I also tried using this() instead of Circle(), which
caused a compiler error. I also tried doing it without the this-> specifier,
which made no difference. The end result if you call the second constructor
is that the X and Y values have been set, and the Radius is uninitialized.
If you use the third constructor, you get exactly the opposite results. (And
I don't mean they have values of zero; looking at them with the debugger, I
see values of -842150451 for the uninitialized members.)

So is there any way in C++ to let one constructor build on another like
this?


Sorry, no. Sometimes you can factor the common initialization out into a
separate init() function, but of course members you don't mention in the
member-initialization list will have been default-constructed by the time
you can call init(). If you have const members, reference members, or
members that don't have default ctors, you must initialize them in each
ctor's member initialization list.

--
Doug Harrison
Microsoft MVP - Visual C++
Nov 17 '05 #3

"Doug Harrison [MVP]" <ds*@mvps.org > wrote in message
news:ct******** *************** *********@4ax.c om...
Peter E. Granger wrote:
I'm fairly new to C++ and VC++, but for the most part it seems to do most ofthe same things that can be done in Java, with just some syntactic and
structural adjustments. However, one thing I haven't been able to figure outis how to call one constructor from another within a class. It's easy enoughto call the base class's constructor from the derived class, but that's notwhat I'm trying to do.
<snip>
Circle::Circle (int x, int y)
{
Circle();


The statement above creates a temporary Circle object, which is

immediately destroyed at the end of the statement.


Right -- that's what I expected would happen. In fact, I thought I'd said
that in my original message, but I see I omitted it.
So is there any way in C++ to let one constructor build on another like
this?


Sorry, no. Sometimes you can factor the common initialization out into a
separate init() function, but of course members you don't mention in the
member-initialization list will have been default-constructed by the time
you can call init(). If you have const members, reference members, or
members that don't have default ctors, you must initialize them in each
ctor's member initialization list.


That's unfortunate. It's really a handy feature. But you can't get
everything in one, language, I guess.

Thanks for the reply.

- Peter
Nov 17 '05 #4

"Carl Daniel [VC++ MVP]" <cp************ *************** **@mvps.org.nos pam>
wrote in message news:uq******** ******@TK2MSFTN GP10.phx.gbl...
Peter E. Granger wrote:
I'm fairly new to C++ and VC++, but for the most part it seems to do
most of the same things that can be done in Java, with just some
syntactic and structural adjustments.
Actually, there are many things you can do in C++ that have no counterpart
in Java at all. You'll discover them in time.


And vice-versa, presumably (like this case).
However, one thing I haven't
been able to figure out is how to call one constructor from another
within a class. It's easy enough to call the base class's constructor
from the derived class, but that's not what I'm trying to do.


There's no way to do this in C++. Unlike Java, in C++ at the start of the
first statement of a constructor's body all of the members have been
initialized (their constructors have been run if they have them). In Java
everything gets default initialized before the constructor body is run,

and then the constructor body (perhaps redundantly) initializes everything.

To get the same "constructo r re-use" effect in C++, you have to put the
initialization code into a (private/protected) member function and call it
from the constructor(s).


Thanks, I figured I might end up having to do that. Bit of a nuisance, but
manageable.

Thanks for the reply.

- Peter
Nov 17 '05 #5
Peter E. Granger <PE******@hotma il.com> wrote:
[...]
Actually, there are many things you can do in C++ that have no counterpart
in Java at all. You'll discover them in time.
And vice-versa, presumably (like this case).


I wouldn't expect that much, though.
[...]
To get the same "constructo r re-use" effect in C++, you have to put the
initialization code into a (private/protected) member function and call it
from the constructor(s).
Thanks, I figured I might end up having to do that. Bit of a nuisance, but
manageable.


Note that C++ has default parameters which,
AFAIK, where introduced especially to solve
this problem:

class Circle {
public:
Circle(int x=0, int y=0, int r=0)
: PointX(x), PointY(y), Radius(r)
{
}
// ...
};
Thanks for the reply.
HTH,
- Peter

Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #6
Peter E. Granger wrote:
"Carl Daniel [VC++ MVP]" <cp************ *************** **@mvps.org.nos pam>
wrote in message news:uq******** ******@TK2MSFTN GP10.phx.gbl...
Actually, there are many things you can do in C++ that have no counterpart
in Java at all. You'll discover them in time.


And vice-versa, presumably (like this case).


There is something called "placement new" which in this context
behaves exactly like calling one c-tor from another, but programmers
are discouraged from using it.

Nov 17 '05 #7
"Hendrik Schober" <Sp******@gmx.d e> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

Note that C++ has default parameters which,
AFAIK, where introduced especially to solve
this problem:


Default parameters were introduced because, at the time, there was no such
thing as method overloading. They just happen to also solve some of the
simpler cases of redundant constructors.

Ken
Nov 17 '05 #8
"Mihajlo Cvetanovic" <ma*@RnEeMtOsVe Et.co.yu> wrote in message
news:40******** ******@RnEeMtOs VeEt.co.yu...

There is something called "placement new" which in this context
behaves exactly like calling one c-tor from another, but programmers
are discouraged from using it.


Placement new is only designed to be used on uninitialized memory. By the
time you get to the first line of a constructor, you have a semi-valid object
in that memory that would be wiped out.

Ken
Nov 17 '05 #9
Ken Alverson <US********@Alv erson.net> wrote:
"Hendrik Schober" <Sp******@gmx.d e> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

Note that C++ has default parameters which,
AFAIK, where introduced especially to solve
this problem:
Default parameters were introduced because, at the time, there was no such
thing as method overloading. They just happen to also solve some of the
simpler cases of redundant constructors.


"The original motivation for default parameters
was exactly because a ctor cannot call another
ctor for the same type." (Francis Glassborow)
http://www.google.de/groups?selm=pM5...on.demon.co.uk
I don't have D&E handy here, but I believe that
function overloading was among the very first
features of C++. Wasn't there even an 'overload'
keyword (considered?) ones but later dismissed
because it wasn't needed?

OTOH, I know the first one only from Francis'
posting and the second only from my memory, so
i might be wrong.
Ken


Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #10

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

Similar topics

11
1870
by: Alexander Stippler | last post by:
Hi I have already posted and discussed the following problems once, but despite really helpful hints I did not get any further with my problem (I at least learned, first to exactly consider why something does not work instead of immediately searching for work arounds) . I have the following code resulting in an ambiguity: -------------------------------------------------------- template <typename Impl> class Vector {};
1
7099
by: david | last post by:
I have a question (not sure if just a newbie one, or a stupid one) whose answer I couldn't find on the C# books and tutorials I could put my hands on. Consider the following useless class (could be a struct as well, if you just comment out the non static parameterless constructor) and the Main() routine : using System;
2
2197
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to instantiate an array of structures; consider the following useless code : using System; struct MyPointS
7
6788
by: Bonj | last post by:
OK I know a constructor can't have a return value but is it feasible such that I have a class whereby //in MyClass1. class MyClass MyClass1(){} ~MyClass1(){} MyClass1(int & Result) {Result = InitMyClass()} int InitMyClass()
17
2204
by: Bill Grigg | last post by:
I have been successfully calling DLL's using VC++ 6.0 and also using VC++7.1 (.NET). I only mention this because I have never felt comfortable with the process, but nonetheless it did work. Recently I started calling an unmanaged DLL from a .NET app. It worked fine. Now I have the situation where I am trying to call a function in one DLL from another DLL. Both are unmanaged and are built with VC++7.1. In the calling DLL I set the property...
12
2709
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
6
2466
by: daveb | last post by:
I'm trying to write some code that calls the constructors of STL containers explicitly, and I can't get it to compile. A sample program is below. One compiler complains about the last two lines (the map constructor calls), saying that I'm trying to take the address of a constructor. Another compiler complains about all four of the last lines, just saying "invalid use of class". What is the correct syntax for calling a container...
7
2688
by: =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post by:
I have a C# logging assembly with a static constructor and methods that is called from another C# Assembly that is used as a COM interface for a VB6 Application. Ideally I need to build a file name based on the name of the VB6 application. A second choice would be a file name based on the # COM interface assembly. I have tried calling Assembly.GetCallingAssembly() but this fails when I use the VB6 client. Is there a way to get this...
3
1414
by: =?Utf-8?B?TmFkYXY=?= | last post by:
Hi, I am trying to manually call a constructor of a template argument, the compiler returns “error C2039: ‘T’ : is not a member...” How can I manually call the constructor of a template argument? Please note that I cannot use the ‘new’ operator ( as long as it allocates memory ), see the following code snnipet as an example of what I am trying to do.
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10313
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8968
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 projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.