creating objects, while making class non-inheritable

Hi,

Below is the code to make a class non-inheritable (by making constructors private) while allowing to create objects of a class. Its been discussed in Scott Meyers book. I have pasted its code below.

I can't create object on heap, unless I allocate memory to the class and call function makeFSA(). To allocate memory, I need to call constructor, but it is declared private. So I can't allocte memory. How do I create objects of class FSA, as the author expects?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class FSA
{
public:
	static FSA* makeFSA();
	static FSA* makeFSA(const FSA& rhs);

private:
	FSA();
	FSA(const FSA& rhs);
};

FSA* FSA::makeFSA()
{
	return new FSA();
}

FSA* FSA::makeFSA(const FSA& rhs)
{
	return new FSA(rhs);
}
Last edited on
Simply call one of the makeFSA functions. The first one instantiates a new FSA; the second
one makes a copy of an existing one.

This is the way I'm calling in the main function:

 
FSA* f = FSA::makeFSA();


It gives link error as below:

error LNK2019: unresolved external symbol "private: __thiscall FSA::FSA(void)" (??0FSA@@AAE@XZ) referenced in function "public: static class FSA * __cdecl FSA::makeFSA(void)" (?makeFSA@FSA@@SAPAV1@XZ)

I have included iostream lib as below:
1
2
#include <iostream>
using namespace std;
Last edited on
you need to give the ctors a body
You need to actually define the constructors (they aren't defined for you).
Works now. Thanks.
What is the reason/advantage of making the pseudo-constructors as "static" in the above class? Static means only single copy exists, how does that help here?
Last edited on
Static member functions do not requires a 'this' pointer, because they are not associated with any individual instance of the class. They're sort of like global functions in the class's namespace.

if makeFSA was not static, you would need an object to call it. IE:

1
2
3
4
5
f->makeFSA();  // <-- nonstatic
// or
f.makeFSA(); // <-- nonstatic
// instead of:
FSA::makeFSA();  // <-- static 


Of course having an object in this case doesn't make any sense, which is why you make the function static.
Thanks
Topic archived. No new replies allowed.