Please tell me, if the following class is monomorphic?
What makes it monomorphic? What does monomorphic actually mean?
class Foo
{
public:
Foo(int n)
{
this->m = n;
}
void print()
{
std::cout << this->m << std::endl;
}
private:
int m;
};
Edit:
in context of a class Boo:
class Boo
{
public:
Boo& Boo::operator=(const Boo &boo)
{
*foo1 = *boo.foo1;
*foo2 = *boo.foo2;
return *this;
}
private:
Foo* foo1;
Foo* foo2;
};
First, in order to answer this question, we need to examine what
monomorphic
really means. To do that, let's break down the word:So, if we assume that mono = one and morphic = transformable (at least for this example - don't kill me over dictionary semantics)
So, we can take this to mean many things, here are a few off of the top of my head:
So, assuming that that answer 3 isn't what we are looking for (in which case you'd have to find a better answer because that article is confusing), let's step through one and two.
1. Our class can only be changed once
In my opinion, this is the most likely meaning. At first glance, your object is monomorphic, meaning it can only be changed once, through the constructor (be that the designated constructor or the built-in copy constructor).
In any computer that has memory that is read-write, this cannot be true, because there's almost always a way to manually set the bits in memory, if you want / need to.
However, barring from that scenario, using the interface you provided, then yes, your class is monomorphic in that it's member (
m
) is only set through the constructor.2. Our class isn't polymorphic
The answer to this one is a bit complex. C++, unlike most languages, has two forms of polymorphism. In a traditional OO sense, it has the ability to create functions that are overwritten by a subclass, which would be marked as
virtual
. You do not do this, however, so OO polymorphism is NOT possible with your class.However, as I said earlier, there is more than one type of polymorphism available in C++. The second type is referred to as
template polymorphism
orfunction polymorphism
, which is used throughout the STL (mainly for iterators), and it works a bit like this:Which is a perfectly valid interface, and it would work as expected. However, there is nothing to prevent the following class from being placed to the function:
Which would obviously print a different value.
In the end, C++ is a complex language, and if you truly want a class to be unable to be polymorphic, you need to have all members and functions be private, which defeats the purpose of having an object in the first place.