11
#include <iostream>

class A {
   public:
      void foo() const {
          std::cout << "const version of foo" << std::endl;
      }
      void foo() {
          std::cout << "none const version of foo" << std::endl;
      }
};

int main()
{
  A a;
  const A ac;
  a.foo();
  ac.foo();
}

The above code can't be compiled, could anyone of you tell me why?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Haiyuan Zhang
  • 40,802
  • 41
  • 107
  • 134

2 Answers2

13

You need to initialize it. This is a known problem with the spec.

Evg
  • 25,259
  • 5
  • 41
  • 83
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • What is the notion behind not allowing it? – Shamim Hafiz - MSFT Mar 17 '11 at 07:00
  • I don't get the wording about user-provided default constructor. If there was empty `A::A()` provided would it compile? – sharptooth Mar 17 '11 at 07:01
  • 1
    @Gunner there just is no wording that allows the special case of an empty class to stay without an initializer or constructor. Classes with data members obviously need to be initialized if you have const objects created. @sharptooth, yes. – Johannes Schaub - litb Mar 17 '11 at 07:01
  • 2
    Ha! Ten years after the defect was reported: "This issue should be brought up again..." I don't think this one's getting fixed for C++0x. – James McNellis Mar 17 '11 at 07:01
  • @James McNellis: I guess it doesn't bother anyone really - you add an empty default constructor and that's it. – sharptooth Mar 17 '11 at 07:09
  • @James: do you often build const object without any data member ? It would not cost much, but it's definitely an edge case. The fact that it depends on a constructor being defined is funny though (in a weird way). – Matthieu M. Mar 17 '11 at 07:28
  • @Matthieu: Nah, and I don't think it should be a "high priority" thing to be fixed, since it's not so much a bug (like an inconsistency is a bug), it's a trivial annoyance. I do think it's funny that it laid dormant for a decade then right before what is hopefully the last committee meeting before C++0x is finished it was commented on, though :-) – James McNellis Mar 17 '11 at 14:35
  • a silly doubt again on this old bug. Don't the compiler generate the default constructor here? Wouldn't the default constructor be called at the line const A ac; to initialize ac ? – irappa Dec 16 '12 at 23:06
4

Initialize it as:

const A ac = A();

Working code : http://www.ideone.com/SYPO9


BTW, this is not initializaiton : const A ac(); //deceptive - not an initializaiton!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • You can also give A a user-defined constructor, even if it does nothing. The fact it has no constructor and the const is not initialised means it does not consider the object initialised. – CashCow Mar 17 '11 at 13:29