473,856 Members | 1,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class with no default constructor as a member in another class?

Hi,

Lets say I have a class a which looks like the following:

class a
{
public:
a(int i)
{
m_nI = i;
}
private:
int m_nI;
};

This class does not have a default constructor. Now I'd like to use the
class in class b as a member variable:

class b
{

private:
a m_a;
};

However since a needs a parameter to get constructed how can I specify this
as a part of class b? I know it's possible to initialize a by using a
pointer as member variable and e.g. new it inside the constructor but I'd
like to have a normal stack based variable.

How do I go about this?

Thanks in advance.

-- Henrik
Sep 8 '06 #1
4 4394

Henrik Goldman wrote:
Hi,

Lets say I have a class a which looks like the following:
<snip>
try:

class a
{
int m_nl;
public:
a( int i ) : m_nl( i ) { }
};

Thats called an init list.
>
This class does not have a default constructor. Now I'd like to use the
class in class b as a member variable:

class b
{
private:
a m_a;
};
class b
{
a member;
public:
b() : member( 0 ) { }
b( int i ) : member( i ) { }
~b() { }
};

Thats 2 ctors for the price of one + a d~tor.
If you Capitalized your Classes (class A instead of class a), you'ld
find it easier to observe what is a type and variable of that type.
>
However since a needs a parameter to get constructed how can I specify this
as a part of class b? I know it's possible to initialize a by using a
pointer as member variable and e.g. new it inside the constructor but I'd
like to have a normal stack based variable.

How do I go about this?
The init list lets you initialize the member(s).
>
Thanks in advance.

-- Henrik
Sep 8 '06 #2

Salt_Peter wrote:
>
class b
{
a member;
public:
b() : member( 0 ) { }
b( int i ) : member( i ) { }
~b() { }
};

Thats 2 ctors for the price of one + a d~tor.
No need for the destructor. One constructor would do:

class b
{
a member;
public:
explicit b( int i ) : member( i )
{
}
};

of course in reality you might put the implementation of b's
constructor in a different file thus:

class b
{
a member;
public:
explicit b( int i );
};

// then somewhere else
b::b( int i ) : a( i )
{}

If you Capitalized your Classes (class A instead of class a), you'ld
find it easier to observe what is a type and variable of that type.
Style preference irrelevant here. Many prefer not to capitalise
classes. But of course in reality you'd give them more meaningful names
than a and b.

Sep 8 '06 #3

Earl Purple wrote:
Salt_Peter wrote:

class b
{
a member;
public:
b() : member( 0 ) { }
b( int i ) : member( i ) { }
~b() { }
};

Thats 2 ctors for the price of one + a d~tor.

No need for the destructor. One constructor would do:
I disagree, its quite important to indicates one's intentions in so far
as the d~tor is concerned:
consider:

class b
{
...
public:
virtual ~b() { }
};

Add to that the need to investigate proper destruction of objects:

#include <iostream>

class b
{
...
public:
...
~b() { std::cout << "~b()\n"; }
};
>
class b
{
a member;
public:
explicit b( int i ) : member( i )
{
}
};

of course in reality you might put the implementation of b's
constructor in a different file thus:

class b
{
a member;
public:
explicit b( int i );
};

// then somewhere else
b::b( int i ) : a( i )
{}
that would not compile. try...
// b.cpp
#include "b.h"

b::b( int i ) : member( i )
{
}
>
If you Capitalized your Classes (class A instead of class a), you'ld
find it easier to observe what is a type and variable of that type.

Style preference irrelevant here. Many prefer not to capitalise
classes. But of course in reality you'd give them more meaningful names
than a and b.
point taken, but then why did you make the mistake of writing:

b::b( int i ) : a( i )
{}

hmm?

Sep 9 '06 #4
Thanks for the suggestions.

In real life I naturally use better class names then a and b and I also
start them with capital names (with a prefixed C):

class CMyTestClass
{

};

-- Henrik
Sep 9 '06 #5

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

Similar topics

50
6402
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the method foo. But the initialization of attr2 is wrong
106
5633
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
15
21210
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 pointers) and for objects types call their default constructor. Any others points i should know?
6
1871
by: Fred | last post by:
Hi I have a class defined in a library that I'd like to add some extra functionality to. This will involve adding a few member variables and a few related methods. As I understand it I can simply inherit from the existing class and add in my new variables and methods - but what about initialisation? Let's say I add new member variables a and b which I want to always have initial values of 0.0. Do I have to override all the...
5
8738
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
8
1514
by: pauldepstein | last post by:
I am writing a program which looks at nodes which have coordinates which are time-dependent. So I have a class called node which contains the private member declarations int date; int month; (I want to consider the month as part of the information contained in the node, as well as the date.) The node class also contains public member function void set_month(int) which sets the month according to the date given.
10
2035
by: imutate | last post by:
Some questions about ctors and class members Is v private in the following ? If it is why put the declaration at the top ? Is there any difference to putting it in the private section ? The reference to v() defines the constructor, it will call v's constructor, right ? class vec {
61
3009
by: Sanders Kaufman | last post by:
I'm wondering if I'm doing this right, as far as using another class object as a PHP class property. class my_baseclass { var $Database; var $ErrorMessage; var $TableName; var $RecordSet; function my_baseclass(){ $this->TableName = "";
12
6266
by: hweekuan | last post by:
hi, it seems i can't assign the const variable u in class A, one way to solve the problem may be to build a copy constructor. however, why does C++ or vector class not like this code? my g++ is: gcc version 4.0.1 (Apple Inc. build 5465). thanks for the help. summary of compile error: --------------------------------------- cpp.C:4: error: non-static const member 'const unsigned int A::u',
0
9762
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11057
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
10782
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
9531
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
7932
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
5761
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
4575
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
4174
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3201
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.