473,583 Members | 4,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

private default constructor is good or bad?

In his book "More Effective C++", Scott Meyer suggests in "Item 4" to
"Avoid gratuitous default constructors".

To summarize his claims against default constructors for "the right
classes" he states that:

=============== === START QUOTE =============
"A default constructor is the C++ way of saying you can get something
for nothing. Constructors initialize objects, so default constructors
initialize objects without any information from the place where the
object is being created. Sometimes this makes perfect sense. Objects
that act like numbers, for example, may reasonably be initialized to
zero or to undefined values. Objects that act like pointers may
reasonably be initialized to null or to undefined values. Data
structures like linked lists, hash tables, maps, and the like may
reasonably be initialized to empty containers.

Not all objects fall into this category. For many objects, there is no
reasonable way to perform a complete initialization in the absence of
outside information. For example, an object representing an entry in an
address book makes no sense unless the name of the thing being entered
is provided. In some companies, all equipment must be tagged with a
corporate ID number, and creating an object to model a piece of
equipment in such companies is nonsensical unless the appropriate ID
number is provided.

Inclusion of meaningless default constructors affects the efficiency of
classes, too. If member functions have to test to see if fields have
truly been initialized, clients of those functions have to pay for the
time those tests take. Furthermore, they have to pay for the code that
goes into those tests, because that makes executables and libraries
bigger. They also have to pay for the code that handles the cases where
the tests fail. All those costs are avoided if a class's constructors
ensure that all fields of an object are correctly initialized. Often
default constructors can't offer that kind of assurance, so it's best
to avoid them in classes where they make no sense. That places some
limits on how such classes can be used, yes, but it also guarantees
that when you do use such classes, you can expect that the objects they
generate are fully initialized and are efficiently implemented."
=============== === END QUOTE =============

Now... I tried to follow this guideline (among others), by declaring a
private default constructor for a class that seems to be useless
without being properly initialized with some values.

However, this created a problem of inability to optimize my application
for speed. The reason is that in my particular case I am re-creating a
database record (represented by the aforementioned class with private
ctor) on the heap in a pretty huge loop. The call to 'new' is very
costly in terms of CPU cycles... I realized I can improve performance
greatly if I instantiate this record only once *outside* the loop.
However, outside the loop I don't have any meaningful values to
initialize that record with, so a default constructor seems to be
required here...

So, my question is: how do I solve the dilemma? On one hand, from the
*logical correctness* point of view, it doesn't make sense for my class
to have a default constructor. On the other hand, from *performance*
point of view a default constructor is required (or using some dummy
values for the non-default ctor, which is basically the same).

Can performance considerations justify violation of "elegant
implementation" ?

Dec 15 '05 #1
3 6783
Oops... Sorry for posting here. After waiting in vain the entire day
for my post to appear on comp.lang.c++.m oderated, I thought my message
was rejected and thus decided to try my luck here. Interestingly
enough, a few minutes after posting here, my message appeared in
comp.lang.c++.m oderated as well... I guess I should have waited longer.
Sorry again for the double-post. You can safely ignore this thread.

Dec 15 '05 #2

swengtoo wrote:
In his book "More Effective C++", Scott Meyer suggests in "Item 4" to
"Avoid gratuitous default constructors". So, my question is: how do I solve the dilemma?


First by realizing that even what seems like a logically good idea
doesn't always apply.

Second, you could implement some sort of static class that does the
optimization you want by "initializi ng" the same pointer with different
data. Doing this without getting ugly could get ugly. Some sort of
factory method of sorts.

Good luck.

Dec 16 '05 #3
Maybe I am missing the point here. but I will give this a try. . .

If you want to construct and not pay for the memory allocation penalty
, why not just create your object local to this function. You create a
local object and then using placement new, you can re-construct the
object over and over again, with whatever constructor. You will not
allocate any memory, and the only penalty you pay is the actual
constructor call.

I think there is some magic involved if you need to call the
onstructor. something like

Is this what you are looking for ?

-Art

#include <new>

class Foo {
public:
Foo ( int a ) : A(a) { }
private :
Foo() ;
int A ;
};

void do_some_foo ( void )
{
Foo local_foo ( -1 ) ; // Local variable
int count_a = 0 ;
while ( 1 ) {
local_foo.Foo:: ~Foo() ; // If you need to call this
new ( &local_foo ) Foo ( count_a++ ) ; // will not allocate
}
}

Dec 16 '05 #4

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

Similar topics

15
21179
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?
34
3077
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is this in any way used to create singletons. Can someone say how? Cheers, Andy
10
2479
by: Ioannis Vranos | last post by:
May someone explain why does this compile? class HiddenSealBaseClass { public: HiddenSealBaseClass() { } }; class Sealed: virtual HiddenSealBaseClass
4
5520
by: plmanikandan | last post by:
Is static constructor available in C++? Can anybody explain me about private and static constructors in c++ Rgds, Mani
12
4204
by: Elad | last post by:
Hello All, Im taking an OOP course, in one of the tutorials, there was a frozen class example, i.e. a class which is impossible to inherit from, the example was something like: struct ice__ { ice() {}; };
3
3382
by: John Salmon | last post by:
g++ complains about illegal access to a private member when the following is compiled with a private copy constructor for the class C. When the copy constructor is public, the program runs and demonstrates(?) that the copy constructor is never called (at least no sign of its chatter on std::cout is visible). So - is it necessary to have a...
4
3698
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for...
10
3439
by: siddhu | last post by:
Dear Experts, I want to make a class whose objects can be created only on heap. I used the following approach. class ss { ss(){} public: void* operator new(size_t sz)
7
4277
by: Rahul | last post by:
Hi Everyone, I was trying to implement a final class and i start having the destructor of the final class as private, class A { ~A() { printf("destructor invoked\n");
0
7825
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...
0
8179
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. ...
0
8323
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...
1
7933
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...
0
6578
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...
0
5372
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...
0
3841
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2331
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
1
1431
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.