Factory method and const specifier

  • Thread starter Martin Herbert Dietze
  • Start date
M

Martin Herbert Dietze

Hello,

I have a factory method like this:

ParentClass* ClassName::mkObject (int foo, int bar) const;

Now when I call it to create an object, g++ seems to treat this
new object as a const reference:

ParentClass *foo = mkObject (42, 42);
foo->addToFoo (42);

....results in this:

error: invalid initialization of reference of
type 'ParentClass&' from expression of type 'const ParentClass'

My understanding is that the `mkObject' method does not modify
the object on which I call it. Why should the returned object
now be a const object?

Cheers,

Martin
 
R

Rolf Magnus

Martin said:
Hello,

I have a factory method like this:

ParentClass* ClassName::mkObject (int foo, int bar) const;

Now when I call it to create an object, g++ seems to treat this
new object as a const reference:

ParentClass *foo = mkObject (42, 42);

Where is your ClassName object? Since mkObject is const, it cannot be a
static function, so it must be called on an object.
foo->addToFoo (42);

...results in this:

error: invalid initialization of reference of
type 'ParentClass&' from expression of type 'const ParentClass'

My understanding is that the `mkObject' method does not modify
the object on which I call it. Why should the returned object
now be a const object?

You didn't provide enough information. Please show more code, preferrably a
short, but complete program.
 
J

John Harrison

Martin Herbert Dietze said:
Hello,

I have a factory method like this:

ParentClass* ClassName::mkObject (int foo, int bar) const;

Now when I call it to create an object, g++ seems to treat this
new object as a const reference:

ParentClass *foo = mkObject (42, 42);
foo->addToFoo (42);

...results in this:

error: invalid initialization of reference of
type 'ParentClass&' from expression of type 'const ParentClass'

No, that is not the right error message, or more likely its a different line
of code. foo is of type ParentClass* not ParentClass&, and as you say
mkObject is returning ParentClass*.

So something else is going on which you haven't provided enough information
to diagnose. Please post a complete compilable program.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top