Re: Passing a pointer of constructor
On May 3, 10:23 pm, seank76 <sean...@gmail.com> wrote:
On May 3, 4:09 pm, "Alf P. Steinbach" <a...@start.no> wrote:
* seank76:
On May 3, 2:51 pm, Gianni Mariani <gi3nos...@mariani.ws> wrote:
seank76 wrote:
While going through my company's existing codebase, I saw a bunch of
weird lines.
Take a look at this one:
class A
{
public:
A(Foo *f) : _f(f) {}
private:
Foo *_f;
};
class B : public A
{
public:
B() : A(&(Foo &)Foo())) {}
};
That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
Bullshit.
Just compiled and ran a test program without any errors using Sun
forte and gcc1.2
Is that g++ 1.2? g++ is currently at 4.1.something, or more.
Any g++ before about 2.6 or 2.7 is totally worthless. Any g++
before 3.0 is hopelessly out of date.
the test program is the following:
#include <iostream>
#include <fstream>
using namespace std;
class A
{
public:
A() {}
void doThat() { cout << "HELLOSE SEAN!" << endl; }
};
class B
{
protected:
A* _a;
public:
B(A *a) : _a(a) {}
};
class C : B
{
public:
C() : B((A *)&(const A &)A()) {}
You added a const. That makes the code syntactically correct,
and means that the compiler is not required to issue a
diagnostic.
void dodo() { _a->doThat(); }
};
int main()
{
cout << "Starting test." << endl;
C c;
cout << "About the run C.dodo() " << endl;
c.dodo();
return 0;
}
The code contains undefined behavior, which means that it might
seem to work. Especially in simple cases. Try adding tracing
calls to the constructors (including the copy constructor, just
in case) and the destructor of A:
class A
{
public:
A() { std::cout << "A::ctor" << std::endl ; }
A( A const& ) { std::cout << "A::copy" << std::endl ; }
~A() { std::cout << "A::dtor" << std::endl ; }
// ...
} ;
With an up-to-date, conformant compiler, you should see the
message from the destructor before the message from A::doThat().
Another thing you might try is to add a member variable to A,
initialize it in the constructor, overwrite it in the
destructor, and output its value in A::doThat(); you should find
that it does not have the correct value. (The reason your code
seems to work, of course, is because you don't actually use
anything in A in doThat(). Just making doThat() virtual might
be enough to cause problems.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34