user1876508
user1876508

Reputation: 13172

Does C++ not allow you to call private functions from the constructor?

I have the following program

#include <iostream>

class Blah {
    private:
        void hello();  
    public:
        Blah();  
};

void Blah::hello() {
    std::cout << "Hello, world" << std::endl;
}

Blah::Blah() {
    hello();
}

int main() {
    Blah a();
    return 0;
}

it compiles fine, but when I run it, the program does not print "Hello, world" into the console as I would have expected. Why is this?

Upvotes: 3

Views: 133

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

Blah a();

This doesn't create an object, it declares a function. Change it to

Blah a;

This is sometimes known as a "vexing parse".

Upvotes: 12

Related Questions