#Private constructors

8 messages · Page 1 of 1 (latest)

full wasp
#

If I want to make a constructor for my class private do I need to provide an implementation? Or can I just put the declaration and no implementation since I’d never use it.

hidden nightBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

lucid knot
#

private constructors ARE used, just not by the user, but by the class itself

#

;compile

#include <iostream>
class foo {
    foo(int a, int b): x{a}, y{b} {}
public:
    int x, y;
    static foo twice(int a) {
        return foo(a, 2*a);
    }
};

int main() {
    foo f = foo::twice(4);
    std::cout << f.y << std::endl;
}
peak garnetBOT
#
Program Output
8
trail veldt
#

honestly you should just let go of the idea that you don't need to provide an implementation just because you don't use it

#

if you declare a function, you should provide an implementation (or = default, = delete or = 0 it)

#

if you already know you're not going to use something, you probably don't want to declare it in the first place, or = delete it