473,698 Members | 2,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constructor - member variable problem

Hello everybody,
I had this problem several times now and did not yet get the reasoning
behind it. I have a class with a pointer as member variable, lets say a
float array. Furthermore, I have two constructors of which the first is
calling the second one...

Here an easy example (so don't worry about the semantics ;) )

Member variables:
float* pFeatVec;
int dimension;

FeatureVector:: FeatureVector(C onfigReader* crd2) {
pFeatVec = NULL;
dimension = 4;
FeatureVector(d imension);
}

FeatureVector:: FeatureVector(i nt dim) {

dimension = dim;
pFeatVec = new float[dimension];
for(int i=0;i<dimension ;i++) pFeatVec[i]=0;
}

If I create a new object e.g. with FeatureVector* test = new
FeatureVector(& confReader); the program behaves as if there would have
never been the array creation in the second constructor. In other
words: Whatever variable-assignment I do in the second constructor, it
is not seen in the resulting object... Thus, I would have to write:

FeatureVector:: FeatureVector(C onfigReader* crd2) {
pFeatVec = NULL;
dimension = 4;
pFeatVec = new float[dimension];
FeatureVector(d imension);
}

FeatureVector:: FeatureVector(i nt dim) {
dimension = dim;
pFeatVec = new float[dimension];
for(int i=0;i<dimension ;i++) pFeatVec[i]=0;
}

in order to let the system work, but apparently this is kind of
shitty...
Btw: The same counts e.g. for dimension. If I only assign a value to it
within the second constructor, it is as well not known in the
outcome-object..

Greetings and please put an end to my non-knowing...

Thanks
Tim

Jul 14 '06 #1
8 1833
* silversurfer202 5:
Hello everybody,
I had this problem several times now and did not yet get the reasoning
behind it. I have a class with a pointer as member variable, lets say a
float
Use 'double', unless you really need to conserve memory.

array.
Use 'std::vector', it's much more safe and convenient.

Furthermore, I have two constructors of which the first is
calling the second one...
As of C++98, a class T constructor can't call another class T
constructor on the same object, i.e., current C++ does not support
constructor forwarding.

Here an easy example (so don't worry about the semantics ;) )
You should always worry about semantics, and in fact the semantics are
the problem you're dealing with here.

Member variables:
float* pFeatVec;
int dimension;
This is not a C++ class definition.

FeatureVector:: FeatureVector(C onfigReader* crd2) {
Pass by reference unless you want to allow a nullpointer as argument.

pFeatVec = NULL;
dimension = 4;
Use an initializer list rather than assignment.
FeatureVector(d imension);
This constructs a temporary FeatureVector.
}

See the FAQ item "Can one constructor of a class call another
constructor of the same class to initialize the this object?" currently
at <url: http://www.parashift.c om/c++-faq-lite/ctors.html#faq-10.3>.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 14 '06 #2
silversurfer202 5 wrote:
Hello everybody,
I had this problem several times now and did not yet get the reasoning
behind it. I have a class with a pointer as member variable, lets say a
float array. Furthermore, I have two constructors of which the first is
calling the second one...
See the comments in the following. But I think you've misunderstood
what you are doing in your ctor.
Here an easy example (so don't worry about the semantics ;) )

Member variables:
float* pFeatVec;
int dimension;

FeatureVector:: FeatureVector(C onfigReader* crd2) {
pFeatVec = NULL;
dimension = 4;
FeatureVector(d imension);
What do you think that line does? You don't think it calls the
ctor for the current object, do you?

Basically, that line is creating a temporary un-named object
of type FeatureVector. Then, when it goes out of scope (at the
end of the ctor) it gets dtor-ed. It is not doing construction on
the current object, but creating a brand new (temporary) one.

If you want to have construction in this fashion, you have to name
the construction functions something other than the ctor name.
(The "named ctor" idiom.)

As so. (Code typed in at terminal, lots of chance of syntax error.)

FeatureVector:: FeatureVector(C onfigReader* crd2)
{
// yada yada
DoFeatureVector Construction(di m);
}

void FeatureVector:: DoFeatureVector Construction(in t dim)
{
// yada yada
}

You don't want one ctor to be calling another ctor.
Socks

Jul 14 '06 #3
Well the example was just meant to illustrate my problem, so don't be
too pickt whether something is a float or double ;)

Thanks for the info, I did not know C++ could not do it (is there a
good reason why?).

Greetings
Tim

PS: Why should one only use references and not pointers?

Alf P. Steinbach schrieb:
* silversurfer202 5:
Hello everybody,
I had this problem several times now and did not yet get the reasoning
behind it. I have a class with a pointer as member variable, lets say a
float

Use 'double', unless you really need to conserve memory.

array.

Use 'std::vector', it's much more safe and convenient.

Furthermore, I have two constructors of which the first is
calling the second one...

As of C++98, a class T constructor can't call another class T
constructor on the same object, i.e., current C++ does not support
constructor forwarding.

Here an easy example (so don't worry about the semantics ;) )

You should always worry about semantics, and in fact the semantics are
the problem you're dealing with here.

Member variables:
float* pFeatVec;
int dimension;

This is not a C++ class definition.

FeatureVector:: FeatureVector(C onfigReader* crd2) {

Pass by reference unless you want to allow a nullpointer as argument.

pFeatVec = NULL;
dimension = 4;

Use an initializer list rather than assignment.
FeatureVector(d imension);

This constructs a temporary FeatureVector.
}


See the FAQ item "Can one constructor of a class call another
constructor of the same class to initialize the this object?" currently
at <url: http://www.parashift.c om/c++-faq-lite/ctors.html#faq-10.3>.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 14 '06 #4
silversurfer202 5 wrote:
Furthermore, I have two constructors of which the first is
calling the second one...
C++ doesn't allow that. The call to the second constructor creates a
temporary object, then destroys it.
Jul 14 '06 #5
In article <11************ *********@s13g2 000cwa.googlegr oups.com>,
"silversurfer20 25" <ki****@web.dew rote:
Well the example was just meant to illustrate my problem, so don't be
too pickt whether something is a float or double ;)

Thanks for the info, I did not know C++ could not do it (is there a
good reason why?).
Is there a good reason to do otherwise? Before the constructor exists,
the object is not constructed, so what would it mean to "call a
constructor" inside a constructor? Would the object be constructed
(because the inner constructor call exited) or would it not be
constructed (because the outer constructor is still executing?)

In languages that *do* allow constructors to be used like that, the
object is considered constructed before the constructor is entered.

PS: don't top-post.
Jul 14 '06 #6
In languages that *do* allow constructors to be used like that, the
object is considered constructed before the constructor is entered.
Yes, I knew constructor-chains from java and was a little confused to
find that they were not supported in C++.
PS: don't top-post.
OK, I promise to better myself! Thanks @all for your help, I now
created an init() method which is called by the constructors..

Thanks again
Tim

Jul 14 '06 #7
In article <11************ *********@75g20 00cwc.googlegro ups.com>,
"silversurfer20 25" <ki****@web.dew rote:
In languages that *do* allow constructors to be used like that, the
object is considered constructed before the constructor is entered.
Yes, I knew constructor-chains from java and was a little confused to
find that they were not supported in C++.
PS: don't top-post.
OK, I promise to better myself! Thanks @all for your help, I now
created an init() method which is called by the constructors..
Just don't try to make that init() method virtual. The virtual mechanism
doesn't work in constructors either.
Jul 14 '06 #8

Daniel T. schrieb:
In article <11************ *********@75g20 00cwc.googlegro ups.com>,
"silversurfer20 25" <ki****@web.dew rote:
In languages that *do* allow constructors to be used like that, the
object is considered constructed before the constructor is entered.
>
Yes, I knew constructor-chains from java and was a little confused to
find that they were not supported in C++.
PS: don't top-post.
OK, I promise to better myself! Thanks @all for your help, I now
created an init() method which is called by the constructors..

Just don't try to make that init() method virtual. The virtual mechanism
doesn't work in constructors either.
Thanks!

Jul 15 '06 #9

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

Similar topics

2
28012
by: André Somers | last post by:
Hi, I'm having a problem that I have a hard time understanding. I am getting a "Fatal error: Call to a member function on a non-object" on a constructor of a class, that looks like this (simplified): class phpBB_Template { var $classname = "Template"; // Root template directory.
4
6144
by: baumann | last post by:
hi all, according the private / protected access control, - private; that is, its name can be used only by members and friends of the class in which it is declared. - protected; that is, its name can be used only by members and friends of the class in which it is
15
3346
by: Alfonso Morra | last post by:
Hi, I have some code from an example, that I want to retrofit into my project. The code from the example has the following line: SharedAppenderPtr myAppender( new RollingFileAppender("MyAppender")) I want to move this line of code to a constructor in a wrapper class, so that I can determine the appropriate Appender name during the object's
4
2954
by: oliver.lin | last post by:
In my simple test code, I tried to define my constructor outside of the class declaration headr file. The header file: file_handler.h ============================================================ 1 #include <string> 2 using namespace std; 3 class file_handler 4 { //Declare member variables 5 private: 6 string file_rd, file_wr; //Define the file name for read
7
4159
by: coinjo | last post by:
i have to overload a constructor that takes a constant static public data member of a class... Can anybody tell me its syntax of prototype and implementation?
4
4386
by: Henrik Goldman | last post by:
Hi, Lets say I have a class a which looks like the following: class a { public: a(int i) { m_nI = i;
10
2423
by: JosephLee | last post by:
In Inside C++ object Model, Lippman said there are four cases in which compile will sythesize a default constructor to initialize the member variables if the constructor is absent: 1. there is a virtual function; 2. virtual inheritance; 3.base class with explicit default constructor;
34
3667
by: =?ISO-8859-1?Q?Marcel_M=FCller?= | last post by:
Hi, is there a way to avoid the automatic copy constructor generation. I do not want the object to be non-copyable. I simply do not want that copying is done by the default copy constructor. But there is a constructor that accepts the base class. This one should be used for copying. In fact i have a set of classes with a common abstract base. The implementations do not have own data members. They only implement
4
5548
by: l.s.rockfan | last post by:
Hello, how do i have to call an inherited, templated class constructor from the initializer list of the inheriting, non-templated class constructor? example code: template<typename T> class A
0
8683
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9170
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...
1
8902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8873
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7740
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, and deployment—without 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...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
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...
2
2339
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.