Default parameters of constructors

  • Thread starter Marcin Vorbrodt
  • Start date
M

Marcin Vorbrodt

I know that the default parameter(s) of a constructor can be either
hardcoded values or function calls. But can they be calls to static class
methods as well... example:

Constructor of my CoordinateFrame class:

CoordinateFrame(const Basis &basis = Basis::ORIGIN(), const Point &origin =
Point::ORIGIN());

Thanks,
Martin
 
M

Marcin Vorbrodt

Mike Wahler said:
&origin

Are you getting compiler errors or what? If so, what are they,
and what exact code causes them?

#include <iostream>

class A
{
public:
static int foo() { return 1; }
};

class B
{
public:
static int foo() { return 2; }
};

class C
{
public:
int membera;
int memberb;

C(int parma = A::foo(), int parmb = B::foo())
: membera(parma), memberb(parmb) {}
};

int main()
{
C c;
std::cout << c.membera << ", " << c.memberb << '\n';
return 0;
}

Output:

1, 2

-Mike

No, no compiler errors at all. I was just wondering if that was allowed by
the C++ standard, or simply a glitch in my compiler;-)

Martin
 
M

Marcin Vorbrodt

Mike Wahler said:
Well, it's good that you check. I'm fairly sure it's valid, I'll
have to check the standard to be sure. No time right now, but
I'll post my findings when I return (unless of course someone else
beats me to it. :) )

-Mike

Great, cant wait to hear back from you.

Martin
 
J

Janusz Szpilewski

Mike said:
Well, it's good that you check. I'm fairly sure it's valid, I'll
have to check the standard to be sure. No time right now, but
I'll post my findings when I return (unless of course someone else
beats me to it. :) )

The C++ standard forbids the default parameters being local variables
(8.3.6/7) or the keyword this (8.3.6/8). I cannot think of any inherent
reason why constructor might clash with a static member function. Seen
from the run-time environment point of view they are completely unrelated.

Regards,
Janusz
 
M

Mike Wahler

[using the return value of a static member function
as a default function parameter]
allowed

Great, cant wait to hear back from you.

What you're doing is valid, according to 8.3.6
Also note that this issue does not only apply
to constructors, but to any function.

-Mike
 

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
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top