Constructor initializations - which way better why?

What is the significance or advantage of using these syntaxes?

1.)

Foo::Foo() : A(5)
{
}

2.)

Foo::Foo()
{
  A=5;
}

Where does it make a difference? Is one better for some things and the
other better for others? Etc.?
TIA,
Harvey

0
harveyab (125)
3/6/2007 2:22:41 PM
vc.mfc 33608 articles. 0 followers. Follow

49 Replies
820 Views

Similar Articles

[PageSpeed] 30

Harvey wrote:

> What is the significance or advantage of using these syntaxes?
> 
> 1.)
> 
> Foo::Foo() : A(5)
> {
> }
> 
> 2.)
> 
> Foo::Foo()
> {
>   A=5;
> }
> 
> Where does it make a difference? Is one better for some things and the
> other better for others? Etc.?

Harvey:

You should get in the habit of doing it the first way;

1. It is the C++ way.

2. It is more efficient for non-POD types

3. const and reference variables have to be done this way.

David Wilkinson

0
no-reply8010 (1791)
3/6/2007 2:39:17 PM
"Harvey" <harveyab@juno.com> schrieb im Newsbeitrag 
news:1173190961.088585.317100@n33g2000cwc.googlegroups.com...
> What is the significance or advantage of using these syntaxes?
>
> 1.)
>
> Foo::Foo() : A(5)
> {
> }
>
> 2.)
>
> Foo::Foo()
> {
>  A=5;
> }
>
> Where does it make a difference? Is one better for some things and the
> other better for others? Etc.?

The difference is that in the first case, A needes a constructor which 
accepts an int (or something to which an int is convertable). Only this ctor 
will be used. In the second case, A's default ctor is used to initialize it, 
and later an assignment operator will be used to set the value of A to 5. So 
you need a default ctor and an assignment operator, which accepts an int. So 
for any non-trivial type, it is very likely that the first form will be 
faster than the second one.

HTH
    Heinz 


0
3/6/2007 2:40:05 PM
"Harvey" <harveyab@juno.com> wrote in message 
news:1173190961.088585.317100@n33g2000cwc.googlegroups.com...

> What is the significance or advantage of using these syntaxes?
>
> 1.)
>
> Foo::Foo() : A(5)
> {
> }
>
> 2.)
>
> Foo::Foo()
> {
>  A=5;
> }
>
> Where does it make a difference? Is one better for some things and the
> other better for others? Etc.?

In principle I prefer the first - in fact these days I usually list 
construct members there even if I am going to amend it with in the body of 
Foo::Foo().   And even if I'm using a default constructor as:

Foo::Foo() : A()
{
}

It reminds me that I'm constructing something :-)

Some things can ONLY be done by (1).  For example if Foo has a member which 
is a reference to something, or if it has a member with no default 
constructor.

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


0
dave1 (356)
3/6/2007 2:44:44 PM
Like so many things in C++ there are just multiple ways to do the same 
thing.  I've heard that #1 is "faster" from some, but I can't imagine that 
assigning an integer is going to be all that slow either way.  My opinion is 
to use the method you think is easier to read and maintain.

Tom

"Harvey" <harveyab@juno.com> wrote in message 
news:1173190961.088585.317100@n33g2000cwc.googlegroups.com...
> What is the significance or advantage of using these syntaxes?
>
> 1.)
>
> Foo::Foo() : A(5)
> {
> }
>
> 2.)
>
> Foo::Foo()
> {
>  A=5;
> }
>
> Where does it make a difference? Is one better for some things and the
> other better for others? Etc.?
> TIA,
> Harvey
> 

0
tom.nospam (3240)
3/6/2007 3:39:45 PM
On Tue, 6 Mar 2007 07:39:45 -0800, "Tom Serface"
<tom.nospam@camaswood.com> wrote:

>Like so many things in C++ there are just multiple ways to do the same 
>thing.  I've heard that #1 is "faster" from some, but I can't imagine that 
>assigning an integer is going to be all that slow either way.  My opinion is 
>to use the method you think is easier to read and maintain.

Hi Tom,

I believe that #1 is faster, because - as Heinz wrote - #1 requires
only a constructor to be called, while #2 requires a default
constructor and then an assignment operator.

Of course, for integers this may be negligible, but for bigger and
more complex classes, the difference may be important.

IMHO, I think that it is good C++ practice to use #1.

MrAsm
0
mrasm (715)
3/6/2007 3:47:29 PM
I can't argue that point.  I find method #2 easier to read and it bothers 
that VS always puts in m_csVar(_T("")) for CStrings which are empty by 
default.  It seems redundant.   But, as you said, it is probably better to 
use #1 if you have a complex set of initializations or if you are going to 
create a lot of the objects.  Otherwise the difference in "speed" is 
probably moot.

Tom

"MrAsm" <mrasm@usa.com> wrote in message 
news:703ru2dgvms6oac6eb71mneppotr2dqoi3@4ax.com...
> On Tue, 6 Mar 2007 07:39:45 -0800, "Tom Serface"
> <tom.nospam@camaswood.com> wrote:
>
>>Like so many things in C++ there are just multiple ways to do the same
>>thing.  I've heard that #1 is "faster" from some, but I can't imagine that
>>assigning an integer is going to be all that slow either way.  My opinion 
>>is
>>to use the method you think is easier to read and maintain.
>
> Hi Tom,
>
> I believe that #1 is faster, because - as Heinz wrote - #1 requires
> only a constructor to be called, while #2 requires a default
> constructor and then an assignment operator.
>
> Of course, for integers this may be negligible, but for bigger and
> more complex classes, the difference may be important.
>
> IMHO, I think that it is good C++ practice to use #1.
>
> MrAsm 

0
tom.nospam (3240)
3/6/2007 4:00:18 PM
"Tom Serface" <tom.nospam@camaswood.com> wrote in message 
news:245BE5A2-20DD-4F29-A2DD-8DDE41CD2878@microsoft.com...

>I can't argue that point.  I find method #2 easier to read

I used to - but nowadays (since I have gazillions of classes with no default 
constructor) I am much happier with (1) - especially as it tells me what is 
happening.

> and it bothers that VS always puts in m_csVar(_T("")) for CStrings which 
> are empty by default.

You can always have m_csVar()  [as CString has a default connstructor].  :-)

>  It seems redundant.

It isn't.  Some constructor is always going to get called - so you may as 
well see which it is!

>But, as you said, it is probably better to use #1 if you have a complex set 
>of initializations or if you are going to create a lot of the objects. 
>Otherwise the difference in "speed" is probably moot.

(2) will only be significantly slower than necessary when an object has a 
long and involved default constructor (which is then overruled by an 
assignment).   I prefer (1) it for general elegance.

Of course one's taste changes. Sometimes I find some very old code where I 
wrote something like:

int  number_of_objects;
number_of_objects = ....;

and I find it very strange, as nowadays I'd always write something more like

int nObjectCount = ....;

Still absolute consistency is just a sign of lack of imagination :-)

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm





0
dave1 (356)
3/6/2007 4:48:38 PM
On Tue, 6 Mar 2007 16:48:38 -0000, "David Webber"
<dave@musical.demon.co.uk> wrote:


>Still absolute consistency is just a sign of lack of imagination :-)

:-)

MrAsm
0
mrasm (715)
3/6/2007 5:41:07 PM
Yeah, this is sort of like a religious thing, but I grant that you are 
correct about the constructor.  The modern compilers are smart enough not to 
have a bunch of blank strings in memory so the whole argument is probably 
moot... :o)

Tom

"David Webber" <dave@musical.demon.co.uk> wrote in message 
news:eoCeKKBYHHA.4868@TK2MSFTNGP03.phx.gbl...
>

> It isn't.  Some constructor is always going to get called - so you may as 
> well see which it is!

0
tom.nospam (3240)
3/6/2007 7:38:21 PM
You are misinterpeting the purpose.
You can do it either way, but there is a reason behind the madness.

Ok, so you have some default class. Let's call it FFT.
Now, you have 2 channels. You want to call one of them Channel 1 and the 
other Channel 2.
Instead of putting the Name in the Constructor, you pass it like in your 
example.
FFT FFTch1("Channel 1")
FFT FFTch2("Channel 2")

Now, you have a way to save data seperately and use them seperately and 
knowing which one is which.
Example of Saving to Ini File.
[FFT Channel 1]
Samples = 1024
[FFT Channel 2]
Samples = 2048

That keeps you from having 2 different FFT classes. 1 for Channel 1 and 1 
for Channel 2.
That is why it is used.

It doesn't make sense with 1 class, but I suppose you could have different 
initializers.
To somehow initiate the class.


Regards, 


0
Nobody530 (222)
3/7/2007 12:58:00 AM
Faster? Based on what premise?  Assigning a value to a variable takes the same number of
instructions no matter where it is done...

The real answer was the one about const and reference variables.  The first form works,
but the second cannot.
					joe


On Tue, 6 Mar 2007 15:40:05 +0100, "Heinz Ozwirk" <SPAMhozwirk@arcor.de> wrote:

>"Harvey" <harveyab@juno.com> schrieb im Newsbeitrag 
>news:1173190961.088585.317100@n33g2000cwc.googlegroups.com...
>> What is the significance or advantage of using these syntaxes?
>>
>> 1.)
>>
>> Foo::Foo() : A(5)
>> {
>> }
>>
>> 2.)
>>
>> Foo::Foo()
>> {
>>  A=5;
>> }
>>
>> Where does it make a difference? Is one better for some things and the
>> other better for others? Etc.?
>
>The difference is that in the first case, A needes a constructor which 
>accepts an int (or something to which an int is convertable). Only this ctor 
>will be used. In the second case, A's default ctor is used to initialize it, 
>and later an assignment operator will be used to set the value of A to 5. So 
>you need a default ctor and an assignment operator, which accepts an int. So 
>for any non-trivial type, it is very likely that the first form will be 
>faster than the second one.
>
>HTH
>    Heinz 
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/7/2007 6:53:23 AM
Just to point out that arguments about "faster" are usually meaningless unless there is
actual analysis, here are two examples, and the generated code is shown.  Note that the
code is identical.  
				joe

class A {
public:
    A() : x(5) {}
protected:
    int x;
    };
class B {
public:
    B() { x = 5; }
protected:
    int x;
    };

; 9    :     A() : x(5) {}

  00000	8b c1		 mov	 eax, ecx
  00002	c7 00 05 00 00
	00		 mov	 DWORD PTR [eax], 5
  00008	c3		 ret	 0

; 15   :     B() { x = 5; }

  00000	8b c1		 mov	 eax, ecx
  00002	c7 00 05 00 00
	00		 mov	 DWORD PTR [eax], 5
  00008	c3		 ret	 0


On Tue, 06 Mar 2007 15:47:29 GMT, MrAsm <mrasm@usa.com> wrote:

>On Tue, 6 Mar 2007 07:39:45 -0800, "Tom Serface"
><tom.nospam@camaswood.com> wrote:
>
>>Like so many things in C++ there are just multiple ways to do the same 
>>thing.  I've heard that #1 is "faster" from some, but I can't imagine that 
>>assigning an integer is going to be all that slow either way.  My opinion is 
>>to use the method you think is easier to read and maintain.
>
>Hi Tom,
>
>I believe that #1 is faster, because - as Heinz wrote - #1 requires
>only a constructor to be called, while #2 requires a default
>constructor and then an assignment operator.
>
>Of course, for integers this may be negligible, but for bigger and
>more complex classes, the difference may be important.
>
>IMHO, I think that it is good C++ practice to use #1.
>
>MrAsm
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/7/2007 7:06:22 AM
On Wed, 07 Mar 2007 02:06:22 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:

>Just to point out that arguments about "faster" are usually meaningless unless there is
>actual analysis, here are two examples, and the generated code is shown.  Note that the
>code is identical.  
>				joe
>
>class A {
>public:
>    A() : x(5) {}
>protected:
>    int x;
>    };
>class B {
>public:
>    B() { x = 5; }
>protected:
>    int x;
>    };

Maybe for a simple type like an integer the compiler outputs the same
code (is it an optimization?), but for a non-simple type, from what I
know of C++ theory, the example A calls only a constructor, while the
example B calls the default constructor and then operator =.

It is exactly what is shown in the following example:

<OUTPUT>

Case A:
NonSimple Ctor


Case B:
NonSimple Default Ctor
NonSimple Ctor
NonSimple operator=

</OUTPUT>


<CODE>

//
// *** TEST C++ OBJECT CONSTRUCTION ***
// [by MrAsm]
//

#include <iostream>
#include <string>
#include <sstream>

using std::cout;
using std::endl;
using std::string;
using std::ostringstream;


//
// A "non-simple" class
//
class NonSimple
{
public:
    NonSimple();
    NonSimple( int nn, const string & ss );
    NonSimple(const NonSimple & src);

    NonSimple & operator=(const NonSimple & src);

    string ToString() const;


    int n;
    string s;
};

NonSimple::NonSimple()
{
    cout << "NonSimple Default Ctor" << endl;
}

NonSimple::NonSimple( int nn, const string & ss )
: n(nn), s(ss)
{
    cout << "NonSimple Ctor" << endl;
}


NonSimple::NonSimple(const NonSimple & src)
: n(src.n), s(src.s)
{
    cout << "NonSimple Copy Ctor" << endl;
}

NonSimple & NonSimple::operator=(const NonSimple & src)
{
    cout << "NonSimple operator=" << endl;
    
    if (&src != this)
    {
        n = src.n;
        s = src.s;
    }
    return *this;
}

string NonSimple::ToString() const
{
    ostringstream os;
    os << "[NonSimple] n = " << n << "; s = " << s;
    return os.str();
}



//
// Case A
//
class A
{
public:

    // C++ typical initialization
    A() : x(1, "Case A") {}

    NonSimple x;
};


//
// Case B
//
class B
{
public:

    // Case A should be better...
    B() { x = NonSimple(2, "Case B"); }

    NonSimple x;
};


//
// TEST
//
int main()
{
    cout << "Case A:" << endl;
    A a;

    cout << endl << endl << "Case B:" << endl;
    B b;

    system("PAUSE");
    return 0;
}


//
// END
//

</CODE>


MrAsm
0
mrasm (715)
3/7/2007 7:40:22 AM
P.S. I have a Grid member variable for each FFT and for other things.
CFFT::CFFT(CString RegSection) : Grid(RegSection)
So that is the reason I use it.
I suppose you can initialize variables that way.
The reason is why you would want to do that?
If you have no need to change the variable, then I say leave it in the 
constructor.
It gets too confusing. Unless that is what you are going for?
I originally thought it was a class you were using instead of just 
initializing some variable.
(I think Java has something like that?)
I would say to leave it in the constructor or overload a constructor to take 
a variable.
Especially when there is no need to do what you are doing.



0
Nobody530 (222)
3/7/2007 10:11:05 AM
I'll take a look at the example.  You didn't show the generated code.
					joe

On Wed, 07 Mar 2007 07:40:22 GMT, MrAsm <mrasm@usa.com> wrote:

>On Wed, 07 Mar 2007 02:06:22 -0500, Joseph M. Newcomer
><newcomer@flounder.com> wrote:
>
>>Just to point out that arguments about "faster" are usually meaningless unless there is
>>actual analysis, here are two examples, and the generated code is shown.  Note that the
>>code is identical.  
>>				joe
>>
>>class A {
>>public:
>>    A() : x(5) {}
>>protected:
>>    int x;
>>    };
>>class B {
>>public:
>>    B() { x = 5; }
>>protected:
>>    int x;
>>    };
>
>Maybe for a simple type like an integer the compiler outputs the same
>code (is it an optimization?), but for a non-simple type, from what I
>know of C++ theory, the example A calls only a constructor, while the
>example B calls the default constructor and then operator =.
>
>It is exactly what is shown in the following example:
>
><OUTPUT>
>
>Case A:
>NonSimple Ctor
>
>
>Case B:
>NonSimple Default Ctor
>NonSimple Ctor
>NonSimple operator=
>
></OUTPUT>
>
>
><CODE>
>
>//
>// *** TEST C++ OBJECT CONSTRUCTION ***
>// [by MrAsm]
>//
>
>#include <iostream>
>#include <string>
>#include <sstream>
>
>using std::cout;
>using std::endl;
>using std::string;
>using std::ostringstream;
>
>
>//
>// A "non-simple" class
>//
>class NonSimple
>{
>public:
>    NonSimple();
>    NonSimple( int nn, const string & ss );
>    NonSimple(const NonSimple & src);
>
>    NonSimple & operator=(const NonSimple & src);
>
>    string ToString() const;
>
>
>    int n;
>    string s;
>};
>
>NonSimple::NonSimple()
>{
>    cout << "NonSimple Default Ctor" << endl;
>}
>
>NonSimple::NonSimple( int nn, const string & ss )
>: n(nn), s(ss)
>{
>    cout << "NonSimple Ctor" << endl;
>}
>
>
>NonSimple::NonSimple(const NonSimple & src)
>: n(src.n), s(src.s)
>{
>    cout << "NonSimple Copy Ctor" << endl;
>}
>
>NonSimple & NonSimple::operator=(const NonSimple & src)
>{
>    cout << "NonSimple operator=" << endl;
>    
>    if (&src != this)
>    {
>        n = src.n;
>        s = src.s;
>    }
>    return *this;
>}
>
>string NonSimple::ToString() const
>{
>    ostringstream os;
>    os << "[NonSimple] n = " << n << "; s = " << s;
>    return os.str();
>}
>
>
>
>//
>// Case A
>//
>class A
>{
>public:
>
>    // C++ typical initialization
>    A() : x(1, "Case A") {}
>
>    NonSimple x;
>};
>
>
>//
>// Case B
>//
>class B
>{
>public:
>
>    // Case A should be better...
>    B() { x = NonSimple(2, "Case B"); }
>
>    NonSimple x;
>};
>
>
>//
>// TEST
>//
>int main()
>{
>    cout << "Case A:" << endl;
>    A a;
>
>    cout << endl << endl << "Case B:" << endl;
>    B b;
>
>    system("PAUSE");
>    return 0;
>}
>
>
>//
>// END
>//
>
></CODE>
>
>
>MrAsm
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/7/2007 3:12:04 PM
But isn't that just using a constructor?  For that matter, you could do

FFT(const CString & s) : name(s) {...}

there's nothing that says the parameters to the initializers have to be compile-time
constants...
			joe

On Tue, 6 Mar 2007 19:58:00 -0500, "Nobody" <Nobody@yahoo.com> wrote:

>You are misinterpeting the purpose.
>You can do it either way, but there is a reason behind the madness.
>
>Ok, so you have some default class. Let's call it FFT.
>Now, you have 2 channels. You want to call one of them Channel 1 and the 
>other Channel 2.
>Instead of putting the Name in the Constructor, you pass it like in your 
>example.
>FFT FFTch1("Channel 1")
>FFT FFTch2("Channel 2")
>
>Now, you have a way to save data seperately and use them seperately and 
>knowing which one is which.
>Example of Saving to Ini File.
>[FFT Channel 1]
>Samples = 1024
>[FFT Channel 2]
>Samples = 2048
>
>That keeps you from having 2 different FFT classes. 1 for Channel 1 and 1 
>for Channel 2.
>That is why it is used.
>
>It doesn't make sense with 1 class, but I suppose you could have different 
>initializers.
>To somehow initiate the class.
>
>
>Regards, 
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/7/2007 3:15:38 PM
On Wed, 07 Mar 2007 10:12:04 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:

>I'll take a look at the example.  You didn't show the generated code.
>					joe

Hi Joe,

You're right: I didn't show the generated code, but I did show
[copy-paste] the output in console mode (<OUTPUT> ... </OUTPUT>
section in my post).

From the output, I think that the calling sequence is the same as
others and I described, without the optimization clearly shown by you
in your post (but in your sample code there was a "simple" integer
data member).

Please correct me if I'm wrong.

Thanks
MrAsm
0
mrasm (715)
3/7/2007 3:30:29 PM
Hey, you're still using 6.0 so what do you care :o)

Tom

"MrAsm" <mrasm@usa.com> wrote in message 
news:f1qsu2t6nqmit674meoum6jogv9ogfgk7h@4ax.com...

> Maybe for a simple type like an integer the compiler outputs the same
> code (is it an optimization?), but for a non-simple type, from what I
> know of C++ theory, the example A calls only a constructor, while the
> example B calls the default constructor and then operator =.
>
> It is exactly what is shown in the following example:
>
> <OUTPUT>
>
> Case A:
> NonSimple Ctor
>
>
> Case B:
> NonSimple Default Ctor
> NonSimple Ctor
> NonSimple operator=
>
> </OUTPUT>
>
>
> <CODE>
>
> //
> // *** TEST C++ OBJECT CONSTRUCTION ***
> // [by MrAsm]
> //
>
> #include <iostream>
> #include <string>
> #include <sstream>
>
> using std::cout;
> using std::endl;
> using std::string;
> using std::ostringstream;
>
>
> //
> // A "non-simple" class
> //
> class NonSimple
> {
> public:
>    NonSimple();
>    NonSimple( int nn, const string & ss );
>    NonSimple(const NonSimple & src);
>
>    NonSimple & operator=(const NonSimple & src);
>
>    string ToString() const;
>
>
>    int n;
>    string s;
> };
>
> NonSimple::NonSimple()
> {
>    cout << "NonSimple Default Ctor" << endl;
> }
>
> NonSimple::NonSimple( int nn, const string & ss )
> : n(nn), s(ss)
> {
>    cout << "NonSimple Ctor" << endl;
> }
>
>
> NonSimple::NonSimple(const NonSimple & src)
> : n(src.n), s(src.s)
> {
>    cout << "NonSimple Copy Ctor" << endl;
> }
>
> NonSimple & NonSimple::operator=(const NonSimple & src)
> {
>    cout << "NonSimple operator=" << endl;
>
>    if (&src != this)
>    {
>        n = src.n;
>        s = src.s;
>    }
>    return *this;
> }
>
> string NonSimple::ToString() const
> {
>    ostringstream os;
>    os << "[NonSimple] n = " << n << "; s = " << s;
>    return os.str();
> }
>
>
>
> //
> // Case A
> //
> class A
> {
> public:
>
>    // C++ typical initialization
>    A() : x(1, "Case A") {}
>
>    NonSimple x;
> };
>
>
> //
> // Case B
> //
> class B
> {
> public:
>
>    // Case A should be better...
>    B() { x = NonSimple(2, "Case B"); }
>
>    NonSimple x;
> };
>
>
> //
> // TEST
> //
> int main()
> {
>    cout << "Case A:" << endl;
>    A a;
>
>    cout << endl << endl << "Case B:" << endl;
>    B b;
>
>    system("PAUSE");
>    return 0;
> }
>
>
> //
> // END
> //
>
> </CODE>
>
>
> MrAsm 

0
tom.nospam (3240)
3/7/2007 3:39:57 PM
On Wed, 7 Mar 2007 07:39:57 -0800, "Tom Serface"
<tom.nospam@camaswood.com> wrote:

>Hey, you're still using 6.0 so what do you care :o)

:)

Yes Tom, it's true I'm absolutely not a C++ template wizard :)
For me VC6 template support for container classes is just fine :)

But this is a different problem, isn't it?
0
mrasm (715)
3/7/2007 3:55:17 PM
Yeah, I just couldn't resist a little rub at your expense :o)

Tom

"MrAsm" <mrasm@usa.com> wrote in message 
news:9tntu2p56ukia2vi19vi75lebolmkatgt3@4ax.com...
> On Wed, 7 Mar 2007 07:39:57 -0800, "Tom Serface"
> <tom.nospam@camaswood.com> wrote:
>
>>Hey, you're still using 6.0 so what do you care :o)
>
> :)
>
> Yes Tom, it's true I'm absolutely not a C++ template wizard :)
> For me VC6 template support for container classes is just fine :)
>
> But this is a different problem, isn't it? 

0
tom.nospam (3240)
3/7/2007 4:43:30 PM
On Wed, 07 Mar 2007 01:53:23 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:

>On Tue, 6 Mar 2007 15:40:05 +0100, "Heinz Ozwirk" <SPAMhozwirk@arcor.de> wrote:
>
>>"Harvey" <harveyab@juno.com> schrieb im Newsbeitrag 
>>news:1173190961.088585.317100@n33g2000cwc.googlegroups.com...
>>> What is the significance or advantage of using these syntaxes?
>>>
>>> 1.)
>>>
>>> Foo::Foo() : A(5)
>>> {
>>> }
>>>
>>> 2.)
>>>
>>> Foo::Foo()
>>> {
>>>  A=5;
>>> }
>>>
>>> Where does it make a difference? Is one better for some things and the
>>> other better for others? Etc.?
>>
>>The difference is that in the first case, A needes a constructor which 
>>accepts an int (or something to which an int is convertable). Only this ctor 
>>will be used. In the second case, A's default ctor is used to initialize it, 
>>and later an assignment operator will be used to set the value of A to 5. So 
>>you need a default ctor and an assignment operator, which accepts an int. So 
>>for any non-trivial type, it is very likely that the first form will be 
>>faster than the second one.
>
>Faster? Based on what premise?  Assigning a value to a variable takes the same number of
>instructions no matter where it is done...
>
>The real answer was the one about const and reference variables.  The first form works,
>but the second cannot.
>					joe

Actually, everything Heinz said was correct and is just as much of the
"real answer" as the const and reference considerations.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/7/2007 5:29:08 PM
On Wed, 7 Mar 2007 08:43:30 -0800, "Tom Serface"
<tom.nospam@camaswood.com> wrote:

>Yeah, I just couldn't resist a little rub at your expense :o)

:-)
0
mrasm (715)
3/7/2007 5:39:20 PM
> there's nothing that says the parameters to the initializers have to be 
> compile-time
> constants...
I never said they had to be.
That is my fault. I did not post every single possible example.

> But isn't that just using a constructor?  For that matter, you could do
>
> FFT(const CString & s) : name(s) {...}
What is the point in doing something like that?

Yeah, I can make my code as obfuscated as possible.
(Is your job secure and do you have the code to prove it?)
There is no sense in doing something like that.
Especially when you proved it takes the same amount of time either way.
It is there to pass initializers to other classes.

It looks more like class initializers instead of variables.
I suppose that is the reason that it works.
It defaults to initializing a variable instead of a class.
It makes no sense to do something like the way the OP is doing.
It serves no purpose.
(I digress. It might save some small amount of time, which is very 
important. NOT!)

I think Java has something like intializers for variables.
Ints are classes and not just ints.

Int a(1);
a.AddOne(); 


0
Nobody530 (222)
3/8/2007 3:23:35 AM
On 6 Mar 2007 06:22:41 -0800, "Harvey" <harveyab@juno.com> wrote:

>What is the significance or advantage of using these syntaxes?
>
>1.)
>
>Foo::Foo() : A(5)
>{
>}
>
>2.)
>
>Foo::Foo()
>{
>  A=5;
>}
>
>Where does it make a difference? Is one better for some things and the
>other better for others? Etc.?
>TIA,
>Harvey

Method (2) is preferable to (1) only when it isn't possible (or at least is
very inconvenient) to use (1). One example is array initialization; it is
impossible to initialize array members in the member-initialization list,
because the language simply does not provide any syntax to do it. Another
would be a computation involving loops that you don't want to factor out
into a function. As others have noted, if you don't mention a non-static
member variable in the member-initialization list, it will be default
constructed (which for built-in types is no initialization, so the method
really doesn't matter for them, but then there are consistency and order
issues to think about). And don't forget, the initialization that occurs in
the member initialization list is done in the order the member variables
are declared in the class, not the order in which the initializers are
written.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/8/2007 5:02:04 AM
On Wed, 07 Mar 2007 23:02:04 -0600, "Doug Harrison [MVP]"
<dsh@mvps.org> wrote:

>And don't forget, the initialization that occurs in
>the member initialization list is done in the order the member variables
>are declared in the class, not the order in which the initializers are
>written.

I think that making assumptions about order of initializations would
lead to very unstable and error-prone code.

....if someone change the order of declaration of member variables in a
class, then the code will not work as expected (if he assumes that
order of initialization is important).

MrAsm
0
mrasm (715)
3/8/2007 9:44:34 AM
"MrAsm" <mrasm@usa.com> wrote in message 
news:ojmvu257ogrh56eomoq738g4ahciomu8lc@4ax.com...
> On Wed, 07 Mar 2007 23:02:04 -0600, "Doug Harrison [MVP]"

> I think that making assumptions about order of initializations would
> lead to very unstable and error-prone code.

Sometimes it's difficult to avoid, but in any case I always try to order my 
constructors the same way the elements are ordered in the class, so that the 
source code gives a visual feedback of what is happening.

[One of the things I really hate - HATE - about MFC is that the View is 
constructed before the Document which it is viewing!  It is HORRIBLE.]  :-(

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm



0
dave1 (356)
3/8/2007 11:26:13 AM
On Mar 8, 3:26 am, "David Webber" <d...@musical.demon.co.uk> wrote:
>
> [One of the things I really hate - HATE - about MFC is that the View is
> constructed before the Document which it is viewing!  It is HORRIBLE.]  :-(
>
Did MS have some reason for that?
Harvey

0
harveyab (125)
3/8/2007 12:11:44 PM
I'm guessing it's because the document calls the view for updating so a 
"view" needs to be there.  Of course, it could have just been arbitrary :o)

Tom

"Harvey" <harveyab@juno.com> wrote in message 
news:1173355904.221287.193220@j27g2000cwj.googlegroups.com...
> On Mar 8, 3:26 am, "David Webber" <d...@musical.demon.co.uk> wrote:
>>
>> [One of the things I really hate - HATE - about MFC is that the View is
>> constructed before the Document which it is viewing!  It is HORRIBLE.] 
>> :-(
>>
> Did MS have some reason for that?
> Harvey
> 

0
tom.nospam (3240)
3/8/2007 3:41:04 PM
On Thu, 8 Mar 2007 11:26:13 -0000, "David Webber"
<dave@musical.demon.co.uk> wrote:

>
>"MrAsm" <mrasm@usa.com> wrote in message 
>news:ojmvu257ogrh56eomoq738g4ahciomu8lc@4ax.com...
>> On Wed, 07 Mar 2007 23:02:04 -0600, "Doug Harrison [MVP]"
>
>> I think that making assumptions about order of initializations would
>> lead to very unstable and error-prone code.
>
>Sometimes it's difficult to avoid, but in any case I always try to order my 
>constructors the same way the elements are ordered in the class, so that the 
>source code gives a visual feedback of what is happening.

I would prefer a different approach, something we could define as "two
steps construction", i.e.

1. Use a default constructor which puts the object instance in a
"safe" initial state - this is called by the C++ compiler, and order
does not matter.

2. Explicitly call a method like Init or Create or something like
this, to do the 2nd step construction.

In this way, we can explicitly controll construction order.

MyClass::MyClass
  // 1. Compiler calls member default constructors
{
  // 2. Explicitly initialize objects in desidered order

  m_obj1.Create(...);
  m_obj2.Create(...);
  ...
  m_objN.Create(...);
}

MrAsm
0
mrasm (715)
3/8/2007 3:56:17 PM
On Thu, 08 Mar 2007 09:44:34 GMT, MrAsm <mrasm@usa.com> wrote:

>I think that making assumptions about order of initializations would
>lead to very unstable and error-prone code.
>
>...if someone change the order of declaration of member variables in a
>class, then the code will not work as expected (if he assumes that
>order of initialization is important).

This can be mitigated by defining all your member variables in the same
place and writing a comment when you introduce order dependence. For
unknown code, it's a good idea to assume order matters until proven
otherwise, because whether you like it or not, it's there.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/8/2007 6:12:16 PM
On Thu, 08 Mar 2007 15:56:17 GMT, MrAsm <mrasm@usa.com> wrote:

>I would prefer a different approach, something we could define as "two
>steps construction", i.e.
>
>1. Use a default constructor which puts the object instance in a
>"safe" initial state - this is called by the C++ compiler, and order
>does not matter.
>
>2. Explicitly call a method like Init or Create or something like
>this, to do the 2nd step construction.
>
>In this way, we can explicitly controll construction order.
>
>MyClass::MyClass
>  // 1. Compiler calls member default constructors
>{
>  // 2. Explicitly initialize objects in desidered order
>
>  m_obj1.Create(...);
>  m_obj2.Create(...);
>  ...
>  m_objN.Create(...);
>}

MFC uses "two phase construction" (Google it) rather pervasively, and it
makes sense for types like CWnd, which wrap HWND objects, whose lifetimes
don't correspond tightly with C++ object lifetimes. See:

INFO: Explanation of Two-Phase Construction in MFC
http://support.microsoft.com/kb/88105

The "benefits" described therein are questionable. Only the very last
sentence in the article really holds up. The article also omits any mention
of the major, glaring drawback to two-phase construction, namely, that an
object isn't fully usable following construction. I wrote more about this
recently:

http://groups.google.com/group/microsoft.public.vc.language/msg/0b321c23d078ddd9

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/8/2007 6:12:16 PM
"Saving a small amount of time" is a tricky issue.  Unless it is quantized in terms of
overall performance, it is a meaningless discussion.  Example: I once spent an entire day
and many builds because some "clever" programmer had figured out how to zero two pointers
in one assigment.  This example is grossly oversimplified, and applied to a different
language and a different architecture, but imagine someone doing a clever Win16
optimization and you have the right sense.

struct cell {
   union
      struct {
      struct cell NEAR * prev;
      struct cell NEAR * next;
     };
   DWORD pointers;
};

(That's as close as I can render the original language into C; note that pointers were 16
bits in this model).  To zero both pointers in one assignment he could write something
like
	struct cell * P;
	P->pointers = 0;
Of course, when we did the equivalent of moving from Win16 to Win32, only ONE of the
pointers got zeroed.  His argument: it saved one line of code and was faster.  Of course,
it was also wrong.  It saved one instruction execution per pointer, and given the number
of pointers allocated per run, it save at least 100us per execution of the program.  By my
reckoning, we would have to run the program continuously (each time it stopped,
immediately restart it) for about 14 years to make up for the CPU time I had used that day
to find this bug.

Code should be written first and foremost to be correct.  The simplest way to accomplish
this is to make sure it is written simply and clearly.  Then it should be written to be
maintainable.  And, in those rare cases where performance matters at all, it should be
written to be fast.  Fifteen years of doing performance measurement convinced me that
nobody has a clue as to how to preoptimize code...only when you do actual measurement do
you have any idea where the time is actually going.  So I rarely pay attention to issues
about "performance" at the lines-of-code level, except in intense computations like DSP,
image convolution, etc.  Architecture can give you orders of magnitude change in
performance; lines of code optimization might, on a good day, give you single-digit
percentage performance improvement.

The issue seems to be more an argument about proper C++ style.  In that sense, the
obfuscation is largely in the eye of the reader.  Someone who is deeply into the C++ model
will find code perfectly readable that others will find incomprehensible.  But I think the
argument is more persuasive over issues of style and not issues of performance.  In the
absence of performance data, arguments about performance are largely meaningless.
					joe


On Wed, 7 Mar 2007 22:23:35 -0500, "Nobody" <Nobody@yahoo.com> wrote:

>> there's nothing that says the parameters to the initializers have to be 
>> compile-time
>> constants...
>I never said they had to be.
>That is my fault. I did not post every single possible example.
>
>> But isn't that just using a constructor?  For that matter, you could do
>>
>> FFT(const CString & s) : name(s) {...}
>What is the point in doing something like that?
>
>Yeah, I can make my code as obfuscated as possible.
>(Is your job secure and do you have the code to prove it?)
>There is no sense in doing something like that.
>Especially when you proved it takes the same amount of time either way.
>It is there to pass initializers to other classes.
>
>It looks more like class initializers instead of variables.
>I suppose that is the reason that it works.
>It defaults to initializing a variable instead of a class.
>It makes no sense to do something like the way the OP is doing.
>It serves no purpose.
>(I digress. It might save some small amount of time, which is very 
>important. NOT!)
>
>I think Java has something like intializers for variables.
>Ints are classes and not just ints.
>
>Int a(1);
>a.AddOne(); 
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/8/2007 7:12:33 PM
Why is this a problem?  The view wouldn't care about the document until OnInitilUpdate,
when it is guaranteed that the document exists...while it seems strange, note that in
solid code the order wouldn't matter.
					joe

On Thu, 8 Mar 2007 11:26:13 -0000, "David Webber" <dave@musical.demon.co.uk> wrote:

>
>"MrAsm" <mrasm@usa.com> wrote in message 
>news:ojmvu257ogrh56eomoq738g4ahciomu8lc@4ax.com...
>> On Wed, 07 Mar 2007 23:02:04 -0600, "Doug Harrison [MVP]"
>
>> I think that making assumptions about order of initializations would
>> lead to very unstable and error-prone code.
>
>Sometimes it's difficult to avoid, but in any case I always try to order my 
>constructors the same way the elements are ordered in the class, so that the 
>source code gives a visual feedback of what is happening.
>
>[One of the things I really hate - HATE - about MFC is that the View is 
>constructed before the Document which it is viewing!  It is HORRIBLE.]  :-(
>
>Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/8/2007 7:15:19 PM
"Harvey" <harveyab@juno.com> wrote in message 
news:1173355904.221287.193220@j27g2000cwj.googlegroups.com...

> On Mar 8, 3:26 am, "David Webber" <d...@musical.demon.co.uk> wrote:
>>
>> [One of the things I really hate - HATE - about MFC is that the View is
>> constructed before the Document which it is viewing!  It is HORRIBLE.] 
>> :-(
>>

> Did MS have some reason for that?

I suspect that when MFC was first designed, the people involved were not as 
guided by principles of object orientation as they might be today.

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


0
dave1 (356)
3/8/2007 10:33:40 PM
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message 
news:9vg0v29tmjph0cgeom4jeaaen647kfm1t8@4ax.com...

> MFC uses "two phase construction" (Google it) rather pervasively, and it
> makes sense for types like CWnd, which wrap HWND objects, whose lifetimes
> don't correspond tightly with C++ object lifetimes. See:
>
> INFO: Explanation of Two-Phase Construction in MFC
> http://support.microsoft.com/kb/88105
>
> The "benefits" described therein are questionable. Only the very last
> sentence in the article really holds up.

Quote honestly, I don't see that any of it holds up.  They wrote a very thin 
wrapper around Windows APIs (and to be fair that made life easier for those 
of us who wrote Windows programs in C before hand - remember 
generic.cpp????).   But they didn't attempt any real form of object 
orientaion in the other part - the application framework.    This article 
reads like a post-hoc justification which has just been made up.

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm




0
dave1 (356)
3/8/2007 10:40:58 PM
"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
news:b3o0v29bu42ud7ehi37aqfcbu69lc4b4d0@4ax.com...

> Why is this a problem?  The view wouldn't care about the document until 
> OnInitilUpdate,
> when it is guaranteed that the document exists...while it seems strange, 
> note that in
> solid code the order wouldn't matter.

If it were object oriented there'd be no "on initial update" - the object 
would be created in a valid state.   Something like

CMyDocument doc( ...constructor arguments... );
CMyView view( doc, .... );

would seem much more reasonable.

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm




0
dave1 (356)
3/8/2007 10:44:23 PM
We have all learned a lot in the last 13 years :o)

Tom

"David Webber" <dave@musical.demon.co.uk> wrote in message 
news:ePcxmXdYHHA.5044@TK2MSFTNGP05.phx.gbl...

> I suspect that when MFC was first designed, the people involved were not 
> as guided by principles of object orientation as they might be today.
>
> Dave
> -- 
> David Webber
> Author MOZART the music processor for Windows -
> http://www.mozart.co.uk
> For discussion/support see
> http://www.mozart.co.uk/mzusers/mailinglist.htm
>
> 

0
tom.nospam (3240)
3/8/2007 11:55:25 PM
The problem is that creation and initialization can be separate in time.  Object creation
is not the same as object binding, and the object cannot be bound at creation time. This
is common in MFC; for example, a CWnd does not create a window, and a CBrush does not
create a brush (I mean 'CBrush br;'...parameters on the constructor will do an actual
creation, but that's a special case).  So I can create an object, but not have the
environment set up to deal with its initialization.  A common case would be a CFile
constructor.  When I create my object, I want a CFile.  But the CFile will not be bound to
a filename until I execute some part of the object.  The notion that everything happens in
constructors leads to some really complex code and a lot of unnecessary convolutions of
logic...I've seen this in Java code in particular.  Creating a object does not imply the
object is ready to couple to something (e.g., a view coupling to a document) any more than
creating the document first implies there is a view to connect it to.  

It is a complex problem when our mathematical models try to couple to the real world.  For
example, third-normal-form and fifth-normal-form databases presume that the data is
complete, consistent, and non-redundant.  I maintain a database of real, physical objects
(books) and one of the things you quickly learn is that the data is not complete, non
consistent, and highly redundant.  Any attempt to "normalize" data with these
characteristics leads quickly to some very convoluted database representations (I've tried
three times, unsuccessfully, to convert it to a standard database; I finally gave up and
am using it in a XML database with object orientation).  Functional programming people had
a lot of trouble with the concept of input and output streams until they changed their
model to take temporal behavior into account.  C++ suffers from a set of limitations as
well, and it would be an issue of language design to eliminate all these rough edges...and
while you can point to specific cases where something might work out, the general problem
is very difficult.  MFC has a lot of problems, but I don't consider the two-phase creation
to be a deep one (the inability to call a superclass with modified parameters, however, is
a serious defect!)
					joe

On Thu, 8 Mar 2007 22:44:23 -0000, "David Webber" <dave@musical.demon.co.uk> wrote:

>
>"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
>news:b3o0v29bu42ud7ehi37aqfcbu69lc4b4d0@4ax.com...
>
>> Why is this a problem?  The view wouldn't care about the document until 
>> OnInitilUpdate,
>> when it is guaranteed that the document exists...while it seems strange, 
>> note that in
>> solid code the order wouldn't matter.
>
>If it were object oriented there'd be no "on initial update" - the object 
>would be created in a valid state.   Something like
>
>CMyDocument doc( ...constructor arguments... );
>CMyView view( doc, .... );
>
>would seem much more reasonable.
>
>Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/8/2007 11:59:03 PM
That is screamingly clear.  I really suspect that most of the programmers didn't
understand C++, or chose to deliberately ignore it.  For example, the use of pointers in
places where reference values would make more sense.  Or failure to overload methods.
					joe

On Thu, 8 Mar 2007 22:33:40 -0000, "David Webber" <dave@musical.demon.co.uk> wrote:

>
>"Harvey" <harveyab@juno.com> wrote in message 
>news:1173355904.221287.193220@j27g2000cwj.googlegroups.com...
>
>> On Mar 8, 3:26 am, "David Webber" <d...@musical.demon.co.uk> wrote:
>>>
>>> [One of the things I really hate - HATE - about MFC is that the View is
>>> constructed before the Document which it is viewing!  It is HORRIBLE.] 
>>> :-(
>>>
>
>> Did MS have some reason for that?
>
>I suspect that when MFC was first designed, the people involved were not as 
>guided by principles of object orientation as they might be today.
>
>Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/9/2007 12:07:37 AM
I concur.

First, do it correctly, then modify it for performance.

I am not happy when it comes to upgrading/updating code either.
Everytime there is a Visual Studio change, I get a bunch of errors.
The latest was log() and log10().

>So I rarely pay attention to issues
> about "performance" at the lines-of-code level, except in intense 
> computations like DSP,
> image convolution, etc.
How did that old saying go?
10% of the code does 90% of the work.
Hence, the development of RISC processors.

I just had my latest Debug / Release issue, where I did not initialize a 
variable to 0.
I got lazy and took a short cut. I paid for it with my time finding the 
error.



0
Nobody530 (222)
3/9/2007 12:51:01 AM
On Thu, 8 Mar 2007 22:40:58 -0000, "David Webber"
<dave@musical.demon.co.uk> wrote:

>
>"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message 
>news:9vg0v29tmjph0cgeom4jeaaen647kfm1t8@4ax.com...
>
>> MFC uses "two phase construction" (Google it) rather pervasively, and it
>> makes sense for types like CWnd, which wrap HWND objects, whose lifetimes
>> don't correspond tightly with C++ object lifetimes. See:
>>
>> INFO: Explanation of Two-Phase Construction in MFC
>> http://support.microsoft.com/kb/88105
>>
>> The "benefits" described therein are questionable. Only the very last
>> sentence in the article really holds up.
>
>Quote honestly, I don't see that any of it holds up.  They wrote a very thin 
>wrapper around Windows APIs (and to be fair that made life easier for those 
>of us who wrote Windows programs in C before hand - remember 
>generic.cpp????).   But they didn't attempt any real form of object 
>orientaion in the other part - the application framework.    This article 
>reads like a post-hoc justification which has just been made up.

Speaking solely about two-phase construction, that last sentence does make
sense for things like CWnd:

<q>
 In addition, two- phase embedded objects reduce problems allocating and
de-allocating objects, tracking object ownership, and deleting Windows
objects appropriately. 
</q>

Think about all the things that happen inside Windows outside the realm of
your C++ code. I'm talking about window creation from a dialog template,
destruction of child windows when their parent windows are destroyed, etc.
It would be difficult if not impossible to subjugate Windows internals to
C++ object lifetime semantics.

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/9/2007 3:44:30 AM
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message 
news:egl1v2p7g8vjn5n611f5nohu0lig03bft6@4ax.com...

> <q>
> In addition, two- phase embedded objects reduce problems allocating and
> de-allocating objects, tracking object ownership, and deleting Windows
> objects appropriately.
> </q>
>
> Think about all the things that happen inside Windows outside the realm of
> your C++ code. I'm talking about window creation from a dialog template,
> destruction of child windows when their parent windows are destroyed, etc.
> It would be difficult if not impossible to subjugate Windows internals to
> C++ object lifetime semantics.

Ok I accept that in one sense.  I suppose that if a CWnd had to be there 
while its m_hWnd represented a window they'd have had to create another 
internal collection of  valid CWnds in parallel with the hWnds already 
handled by Windows, and having both collections hanging around wouldn't be 
very object oriented either.

So the hWnd is the "object" and the CWnd is just a sort of optional 
interface on an hWnd.   OTOH they could have forced AFAICT a CWnd 
constructor to take an hWnd argument, so that at least it always represented 
an interface on something and not on nothing :-)

Dave

-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm
 


0
dave1 (356)
3/9/2007 8:17:42 AM
"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message 
news:5781v29vmeob2ppcklt5ncbobidn40t96h@4ax.com...

> The problem is that creation and initialization can be separate in time. 
> Object creation
> is not the same as object binding, and the object cannot be bound at 
> creation time.

Yes I know.    But the very concept of "object binding" as separate from 
"object creation" is a step away from the goal of having all objects 
meaningful at all times.

> This
> is common in MFC; for example, a CWnd does not create a window, and a 
> CBrush does not
> create a brush (I mean 'CBrush br;'...parameters on the constructor will 
> do an actual
> creation, but that's a special case).

It shouldn't be special.  It should be normal.

> So I can create an object, but not have the
> environment set up to deal with its initialization.

But the object is useless until the environment exists, so why not wait 
until it does and then create it in one go?  Sometimes in programs with many 
different kinds of object, this does force one to think quite hard about the 
structure of the program, but in my exerience that usually pays dividends.

I concede that it isn't always completely possible.

>  A common case would be a CFile
> constructor.  When I create my object, I want a CFile.

Why?  What use to an object is a CFile which is not a file?

> But the CFile will not be bound to
> a filename until I execute some part of the object.  The notion that 
> everything happens in
> constructors leads to some really complex code and a lot of unnecessary 
> convolutions of
> logic...

I concede that it can do, and in some cases it is unavoidable, but often 
that points to a poor design

> It is a complex problem when our mathematical models try to couple to the 
> real world.

Yes.   I agree that most of the purist OO diatribes use examples with about 
one kind of object, and have nothing to do with the real world, and that 
pragmatism is necessary - but I still feel the doc-view arcitecture could 
have been modelled more helpfully.

To give a "failure" of my own:   in an attempt to generalise away from just 
Windows, I wanted a windows-independent N.DLL to do my number crunching, 
containing classes which would work on any platform.  Then I wanted the 
drawing code and a lot of the comand handling to be done in M.DLL which 
could then be used by various related programs E1.EXE, E2.EXE with different 
menus and toolbars.   [M does drawing so it is definitely for Windows at the 
moment.  So I derived CMView and CMDocument in M.DLL, and derived from them 
CE1View CE1Doc in E2  and CE2View etc in E2.]

It all seemed very neat and logical until somewhere the number crunching in 
N.DLL needed to know how much space a string (say) took up.   At this point 
it needs an hWnd and an hDC to find out and it cannot escape from Windows! 
It has to ask upwards either by virtual members and derived classes in M, or 
by secretly keeping an hWnd and asking up the chain by sending a WM_APP 
message, or by using GDI functions and defeating my object altogether.

Bloody annoying.  It will be easier to wait until all manufacturers run 
Windows apps as native - the mac is already headed that way :-)

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm







0
dave1 (356)
3/9/2007 8:43:33 AM
On Fri, 9 Mar 2007 08:43:33 -0000, "David Webber"
<dave@musical.demon.co.uk> wrote:


>Bloody annoying.  It will be easier to wait until all manufacturers run 
>Windows apps as native - the mac is already headed that way :-)
>
>Dave

:-)

Dave: but what about using a kind of "virtual enviroment" like the
Java Virtual Machine or the .NET Framework?
If your application is built on top of a virtual machine (being it JVM
or .NET), if the virtual machine is implemented on a given computing
platform/operating system (Windows, Linux, MacOS, etc.), your
application would simply run on that operating system, without any
rebuilding!

Some years ago a friend of mine built a pet-project e-mail reader
(with Swing GUI) in Java, all the development process was done on
Windows. We tested the Java app on Windows, and it ran fine.

Then we ran the Java compiled byte-code (without any
recompilation/rebuilding, it was just copying the binary executable
file produced on Windows platform by Java compiler !) on a Linux
partition I had for testing Linux, and the program "magically" :) ran,
as good as on Windows.

I think that virtualization is a very important and useful technology.

I also noted that some very important software like MATLAB uses Java
for the GUI part (I think the kernel is standard C++).

If portability is an important aspect in a project, I think that there
are better solutions than using MFC (e.g. use Java, or QT toolkit - I
believe that Google Earth uses QT).

But if one wants the full control and full power of Windows, then
MFC/ATL are very good IMHO.

MrAsm
0
mrasm (715)
3/9/2007 10:15:55 AM
"MrAsm" <mrasm@usa.com> wrote in message 
news:r3c2v2pjj28j2hmua50dppejbg178cijv8@4ax.com...


>>Bloody annoying.  It will be easier to wait until all manufacturers run
>>Windows apps as native - the mac is already headed that way :-)
>>
>>Dave
>
> :-)
>
> Dave: but what about using a kind of "virtual enviroment" like the
> Java Virtual Machine or the .NET Framework?
>...

I thought a bit about .NET when the first version came out.    I realised 
that porting my application to it would be a nightmare.   I have classes 
with bit fields and multiple inheritance (I'm one of an apparent minority 
who has no religious objection to this) all over the place.   The C++ in 
..NET was just, as far as I could tell, C# with a slightly modified syntax, 
and not C++ at all!

Now my impression is that things have improved a bit, but I suspect that I 
would end up with 90% native C++ anyway after a lot of work.   As long as 
such a large fraction of people use Windows, and the dedicated among the 
others can run my stuff under things like WINE (some do)  I think my time is 
better spent elsewhere.   So MFC is it for the moment.

I've noticed there's an mfcm80.dll these days which looks like it is to do 
with .NET.   Does this provide a sensible conversion path from MFC to .NET?

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


0
dave1 (356)
3/9/2007 12:39:23 PM
There are some interesting stories from Microsoft about the lengths they will go to in
order that badly-written game software will continue to run.  But keep developers running?
We don't count.  VS.NET is a key example of the low regard we are held in.  It is
offensive that the newer MFC and newer VC++ compiler are wrapped in such an awful
interface.
					joe
On Thu, 8 Mar 2007 19:51:01 -0500, "Nobody" <Nobody@yahoo.com> wrote:

>I concur.
>
>First, do it correctly, then modify it for performance.
>
>I am not happy when it comes to upgrading/updating code either.
>Everytime there is a Visual Studio change, I get a bunch of errors.
>The latest was log() and log10().
>
>>So I rarely pay attention to issues
>> about "performance" at the lines-of-code level, except in intense 
>> computations like DSP,
>> image convolution, etc.
>How did that old saying go?
>10% of the code does 90% of the work.
>Hence, the development of RISC processors.
>
>I just had my latest Debug / Release issue, where I did not initialize a 
>variable to 0.
>I got lazy and took a short cut. I paid for it with my time finding the 
>error.
>
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
3/9/2007 4:09:55 PM
Hi Dave,

I'm not sure there is a "sensible" conversion.  However, I think that the 
world will eventually go to managed code although I don't know how long that 
will take.  I think MFC will either evolve or die (although it has a lot of 
life left in it).  I remember back in the mid 80's thinking that this new 
thing Windows would never catch on since it was too much of a machine hog. 
I bought the first version fo Word for Windows and continued using the DOS 
version since it took about 2 minutes just to open an empty file.  However, 
I started learning Windows programming since I had a contract and I'm glad I 
did since I don't know too many people who still use DOS programs.  So, I am 
continue to use MFC while learning .NET and my guess is eventually (although 
it may take several years) managed code will be normal and what we're doing 
now will evolve or be redone or not be used any more.  That's how technology 
works.  I also remember my first 386 based computer. I thought I was in 
heaven... using it wouldn't seem like heaven any more :o)

Tom

"David Webber" <dave@musical.demon.co.uk> wrote in message 
news:eFwwbVlYHHA.3848@TK2MSFTNGP02.phx.gbl...
>
> I thought a bit about .NET when the first version came out.    I realised 
> that porting my application to it would be a nightmare.   I have classes 
> with bit fields and multiple inheritance (I'm one of an apparent minority 
> who has no religious objection to this) all over the place.   The C++ in 
> .NET was just, as far as I could tell, C# with a slightly modified syntax, 
> and not C++ at all!
>
> Now my impression is that things have improved a bit, but I suspect that I 
> would end up with 90% native C++ anyway after a lot of work.   As long as 
> such a large fraction of people use Windows, and the dedicated among the 
> others can run my stuff under things like WINE (some do)  I think my time 
> is better spent elsewhere.   So MFC is it for the moment.
>
> I've noticed there's an mfcm80.dll these days which looks like it is to do 
> with .NET.   Does this provide a sensible conversion path from MFC to 
> .NET?
>
> Dave
> -- 
> David Webber
> Author MOZART the music processor for Windows -
> http://www.mozart.co.uk
> For discussion/support see
> http://www.mozart.co.uk/mzusers/mailinglist.htm
>
> 

0
tom.nospam (3240)
3/9/2007 4:55:37 PM
On Fri, 9 Mar 2007 08:17:42 -0000, "David Webber"
<dave@musical.demon.co.uk> wrote:

>So the hWnd is the "object" and the CWnd is just a sort of optional 
>interface on an hWnd.

I think that's an accurate way to look at it.

>OTOH they could have forced AFAICT a CWnd 
>constructor to take an hWnd argument, so that at least it always represented 
>an interface on something and not on nothing :-)

How would that work for things like CDialog and its CWnd-derived member
variables?

-- 
Doug Harrison
Visual C++ MVP
0
dsh (2498)
3/9/2007 6:34:29 PM
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message 
news:95a3v2h2nbm70f2ng8abb3j00m3g1j21jg@4ax.com...
> On Fri, 9 Mar 2007 08:17:42 -0000, "David Webber"
> <dave@musical.demon.co.uk> wrote:

>>OTOH they could have forced AFAICT a CWnd
>>constructor to take an hWnd argument, so that at least it always 
>>represented
>>an interface on something and not on nothing :-)
>
> How would that work for things like CDialog and its CWnd-derived member
> variables?

You're right - it needs more thought than I have given it - but I knew that 
:-)

In the case of dialogues it seems clear (but maybe also needs thought) that 
a constructor which took a sort of dialogue template class (or a resorce ID 
of one) as an argument and actually constructed a dialogue window (and a 
destructor which removes it) would be more intuitive.  A hidden window would 
then have been initialised before DoModal  is called.  (Modeless dialogues 
would be created with new, and a pointer to them stored).

I am starting to think that I am so used to effectively constructing the 
dialogue in "OnInitDialog" that I have forgotten how completely unintuitive 
I first found it :-)

But there's no point in speculating further - a new alternative to MFC, 
however object oriented, is not going to be a commercial success.  :-)   In 
fact I moved here from the Borland compiler in 1995 as that was already 
clear then :-)

I haven't really started exploring .NET yet (too much to do on MFC code). 
Is window creation there done in two stages with late binding too?

Dave
-- 
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm
 


0
dave1 (356)
3/10/2007 7:53:22 AM
Reply:

Similar Artilces:

Is there a way to make this non-volitile
This is the UDF Function ROll2D6() ROll2D6 = Application.RoundUp(Rnd() * 6, 0) + Application.RoundUp(Rnd() * 6, 0) End Function At current, when Excel recalculates, the random number generated by this function, is replaced by another rnadom nuber. Is there some sort of check that I can put into the UDF whereby IF the current value of the cell (calling the function) is a number, it will return that number instead of a new one.? Thanks You want the number to stay the same after it is entered, correct? One way to do that would be to call it from a sub. In the same module you de...

Is There A Way to Test if Global Catalog Functioning Correctly
Still dealing with some cleanup issues from a DC loss last week. The DC was a Global Catalog server. However, I *believe* we had another one in place. At least, there was a checked GC box under the NTDS properties. However, I was wondering if there is some sort of test to make sure a GC is available and functioning before I proceed with the metadata cleanup of the dead domain controller? Not that it matters much at this point, I suppose. Still, it would be nice to go into this feeling comfortable about having a GC available. Thanks Hello Mark, See the last part ...

OnHScroll/OnVScroll - position is only 16 bits??????
Hi, i've got a ListBox with a very large number of potential items (60000+) and I've noticed that the scroll position that is passed to OnHScroll/OnVScroll is only 16bit even though it's passed in as UINT32 - what kind of solutions are available for this problem? There must be some way around it because i've used windows applications that display more than 32767 items and use scroll-bars. Regards, Karl. me wrote: > Hi, i've got a ListBox with a very large number of potential items (60000+) > and I've noticed that the scroll position that is passed t...

Any way to find "not" character in Search and Replace?
Version: 2004 Operating System: Mac OS X 10.4 (Tiger) Processor: Power PC The &quot;not&quot; character is ASCII 194. It looks a bit like the capital letter L on its side. The character is obtained by typing option-L on the keyboard. <br><br>I have a document with a lot of &quot;not&quot; characters instead of hyphens and I want to replace them with no character, that is, with nothing. The trouble is Word's Search and Replace can't find the &quot;not&quot; characters in the document even though I can type it into the Find box. <br><br&g...

Simple date entry WAY off
Entering today's date as "013006" in a blank cell/new workbook, an changing formatting to ANY type, returns crazy date of "8/10/1935"? All PCs across our company appear to be doing this "all of sudden." Date/regional settings are all normal still. Only recent change was a update to ASAP Utilities, but I can't see how that would affect thing since it's just a plugin. Thoughts/suggestions? Thanks -- ulinetek ----------------------------------------------------------------------- ulineteks's Profile: http://www.excelforum.com/member.php?action=g...

Any way to restore the 35-color color picker?
I recently got Office 11 and would dearly like to find a way to get the older 35-color font-color chart back. I've been using that one for many years and like the choice of colors on it. The "Standard colors" bar at the bottom of the Office 11 theme colors only has 10 colors. Same (plus white) with the "Apple" choice under Palettes. I played with the Theme color choices a little bit; did I overlook one that would restore the old palette? The color samples on it are so tiny that it's hard to tell... Patty In article <4e5ea971$0$2145$742ec2ed@news.sonic.ne...

BestHDSoft,Best way rip blu ray movies to enjoy your life!
<p><a href="http://www.besthdsoft.com">BestHDSoft</a> just like other companies of multimedia industry has begun to focus on the growing Blu-ray Disc market. In mid-last year, BestHDSoft introduced one of the industry's best all-in-one <a href="http://www.besthdsoft.com/best-hd-blu-ray-dvd-ripper.html"><strong>Blu-ray DVD Ripper</strong></a>. Featuring of remove the DRM and the high quality output available, this new super ripper has been well received by users.<br /> Needless to say, this is only a taste of what'...

Changing two way tables into one way tables
Hello - I need to be able to 'undo' a two way table. The data is in this format: Student number English Grade Maths Grade US456 A B+ US455 A- C+ And I need it to look like this: US456 English Grade A US456 Maths Grade B+ US455 English Grade A- US455 Maths Grade C+ So each grade has a separate row - other than copying and pasting hundreds of records is there a simple way to do this? =A2&" "&$B$1&" "&B2 where : A2 = "First Student in your table"; $B$1="English Grade" and B2="English grade for first student and drag th...

How do you change the way email addresses are displayed? John Doe.
How do you change the way a recipent of an emails name is displayed in an email? I want to only show "John Doe" and not "John Doe (Email):<John Doe@xxx.com>" Displayed where and in what version of Outlook? -- Russ Valentine [MVP-Outlook] "dmoors" <dmoors@discussions.microsoft.com> wrote in message news:540E8B6B-2F78-4541-9116-3A79F4A5D52B@microsoft.com... > How do you change the way a recipent of an emails name is displayed in an > email? I want to only show "John Doe" and not "John Doe (Email):<John > Doe@xxx.com>&q...

Like criteria on a combo box ot working the way I want... Please help!
All, Below is a the standard code I use in a combo box. Dim rs As Object Set rs = Me.Recordset.Clone rs.FindFirst "[llListingID] = " & str(Nz(Me![cboTerritoryName], 0)) If Not rs.EOF Then Me.Bookmark = rs.Bookmark Me.Form.AllowAdditions = False The query used to find the data is... SELECT qryLister.llListingID, qryLister.llTerritoryName FROM qryLister WHERE (((qryLister.llTerritoryName) Like "*"+[Enter any part of Territory Name:]+"*")); All works fine for the first look-up. But in order to refresh the combo box so it allows one to &...

Is there some way to switch Ethernet full and half duplex ?
hi Is there some IO control or API to switch Ethernet speed and duplex ? Thank for your teaching . Kid <Kid@discussions.microsoft.com> wrote: > >Is there some IO control or API to switch Ethernet speed and duplex ? No. Why would you want that? The driver picks the best it can do. A driver might have its own internal restrictions for diagnostics, but there's no API. -- Tim Roberts, timr@probo.com Providenza & Boekelheide, Inc. There should probably be the WMI verbs for this. These values are present in Details tab for I think nearly any = ...

Can you change the way quick parts and/or auto text displays?
Is there a way to change the look of the drop down menu for quick parts and auto text so it does not take up so much space? Something like it looked in 2003? Assuming that you have discovered the building block organizer - see http://gregmaxey.mvps.org/Buiild_Employ_Custom_BB_Gallery.htm Like 2003 it ain't! -- <>>< ><<> ><<> <>>< ><<> <>>< <>><<> Graham Mayor - Word MVP My web site www.gmayor.com Word MVP web site http://word.mvps.org <>>< ><<> ><<&...

Any way, with 2003, to download larger clipart library rather than a few at a time?
With Office 97, I was able to download a very large clipart folder (900+mb) when installing the program, and it was very nice not having to insert the disc or deal with the internet. Is it possible to do this with Office 2003? I suppose they don't have that type of data base on the disks (I couldn't find it anyway), since they are relying more on the web interface, but I can't find out where, on the web site, to download a large "general" library. What is the point of having an 80 GB disk if you can't use it! :0) There is a limit, 120 images or 3.5 MGB each vis...

Modifing data to show up better in chart.
My Y1 axis is from 0-250 my Y2 axis is from 0-9000 When graphing percentages the line shows up at the very bottom since 99% < 1 is there a way I can multiply these percentages by 100 to show them as 9900% = 99 Normally you would just make then a 2nd axis but as you can see I already have a second axis of 0-9000 In article <A9E6F75B-7307-4291-BC7D-729F9DF88D50@microsoft.com>, MikePunko@discussions.microsoft.com says... > My Y1 axis is from 0-250 my Y2 axis is from 0-9000 > When graphing percentages the line shows up at the very bottom since 99% < 1 > is there a way I...

What is the best way to do this upgrade?
I have a client with CRM 1.2 running in one domain. They now want to upgrade to CRM 3.0 and move the CRM application to a box residing in a different domain. What is the best way to do this ? My idea is as below: Take back up of 1.2 databases (Production) Install SQL Server on another box in the same domain, restore 1.2 db, install CRM 1.2 pointing to existing database. Test the application thoroughly to check it is same as Production Upgrade to CRM3.0. Test again thoroughly. Take the backup of CRM3.0 database Install SQL Server with appropriate sp etc on a box in another domain Restore CRM...

Something better than Filtering?
Posted with an Unregistered Version of NewsHunter - The Newsgroup Utility for OS X. Get your copy today at: http://www.parkersoftware.com/products/newshunter/ Situation: Sheet A has a simple database which gets updated frequently. In Sheet B, I just want to display the entire rows of the database which meet a certain criteria for 1 column. I tried setting up filters, which work fine, but when I change the database, I have to always update the filter to get the new updated result. This wouldn't be a big deal, except that I will eventually have not only Sheet B to update, but many more. I&#...

Debt Planner
Everytime I try to use the debt planner, it automatically allocates a huge payment in the next month. I'm trying to play with getting out of debt by a certain date, but it always puts something like $13,000 paid off next month. How can I get it calculate correctly? Thanks for the help! Melissa We are having the same problem. Have you been able to fix it? Ryan >-----Original Message----- >Everytime I try to use the debt planner, it automatically >allocates a huge payment in the next month. I'm trying to >play with getting out of debt by a certain date, but i...

Best way to archive?
Hi all, using VC++ 6 SP6. I'm writing an email program. Well actually adapting a very fine package to my needs, which handles all possible email operations. The package comes with a nifty .lib and .dll, but the scheme it uses to save email messages uses a distinct file for each email message. I would like to use something a little different... as you can imagine. I was thinking a database maybe, would that be faster than reading and parsing a zillion small files? Or should I use a CFile object instead? I nned to be able to handle user requests to delete previously saved emails ...

Preferred way to toggle BOOL?
I've used the ^ operator to toggle a BOOL value from 0 to 1 and back to 0. I encountered some code that used the ! operator, and I wondered if there was a preferred way, or if they were equivalent. I suppose the ! operator is clearer. Perhaps the generated object code is slightly smaller/faster with one or the other? IIRC, that was the justification for using the ^ operator, but my impression is that the optimizer can take care of that (minor/negligible) concern. I just used the debugger to step though the following code, and both seemed to work fine with MFC vc71. I didn't lo...

! Too Many Ways to Do Simple Tasks
Hi, I�m currently extending my customized CListCtrl class, but am having difficulty trying to design some of it because there are too many ways to do things. For example, I am trying to allow the control to handle its own sorting for columns that contain basic types like numbers and CStrings. That way, many apps don�t need to bother with handling sorting at all. However there are too many combinations of places where the action occurs. Specifically, the control itself has an OnLvnColumnclick handler, but the parent dialog would have one too if it needs to sort custom types (eg specially-for...

How to make Workbooks smaller / Excel performance better
I have a workbook that is accessed by a lot of users using different spec machines. The workbook is periodically updated with data added from different sources in an automated fashion using macros. Of late the file has grown from 23megs to a whopping 93megs, although as far as I can tell the new worksheets and charts added should *logically* constitute no more than a 20% increase in size from the previous incarnation, and anyway most of the data is stored as values (i.e. formulas removed after processing). This growth in file size has resulted in increased loading times and system slowdowns ...

std::list
Hi, I'm currently using the std::list classes and functions at a point in my application where a high speed is necessary - but unfortunately these functions don't seem to be appropriate for this. Are there any faster alternatives? thanks a lot Peter Peter Schmitz wrote: >Hi, > >I'm currently using the std::list classes and functions at a point in my >application where a high speed is necessary - but unfortunately these >functions don't seem to be appropriate for this. Are there any faster >alternatives? It's hard to say what's fast when you ...

Server Initiate to Client
Is there ever a time that the Server will initiate to a client instead of the other way around? What do you mean? deb wrote: > Is there ever a time that the Server will initiate to a > client instead of the other way around? ...

Good Way to Start MFC Programming
Hi there, I'm pretty new with MFC and I was wanting to start off my project on a good foot, so I was wondering if there are any good MFC books out there for beginner/intermediate MFC programmers. and preferably one that also teaches how to take advantage of Visual Studio's features. Any of you guys have some good recommendations? Thanks, Nick If you are using VS 2008 with the MFC Feature pack there is a new Scribble tutorial that is quite good that showcases the new controls. Lots of people recommend Jeff Prosise's book "Programming Windows With MFC" as wel...

is there a way of using a second monitor as a customer display
This is a multi-part message in MIME format. ------=_NextPart_000_018F_01C86B1D.3EAD2F60 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Hello, Does anyone know if rms works with 2 monitors. What I mean can you use a second monitor as customer display or something similar. A lot of pos systems out there use a second monitor as customer display, I m not sure if rms supports that option or not but any help would be appreciated. thanks ------=_NextPart_000_018F_01C86B1D.3EAD2F60 Content-Type: text/html; charset="us-ascii" Content-Transfer-...