Reputation: 7513
Inspired by this article, I have a class which contains a nested copyable data class. This copyable class has no dynamic memory allocation, protect or private for its member class.
Class Domain
{
public:
// copyable class
struct CopyableDataClass
{
int i;
}
void method1(const CopyableDataClass& data){...}
void method2(const CopyableDataClass& data){...}
}
Also, by reading this Wikipedia page, I could not use dynamic memory allocation for "CopyableDataClass" itself, to avoid the shallow copy, like
Domain::CopyableDataClass* p1=new CopyableDataClass();
Domain::CopyableDataClass* p2;
p2=p1;
But what about the "Domain" Class, is it also special, e.g., can I do it as follows?
Class User
{
public:
Domain* getter();
void setter(const Domain* data);
private:
Domain* m_data; //pointer ok? private ok?
}
Or I have to put it into public like the copyable class,
Class User
{
public:
Domain m_data;
}
Besides the general class design rule (encapsulation, etc.), is there any constraint (protect/private/dynamic memory allocation) to the usage of this "Domain" class. I guess the constraints only apply to the "Copyable" class. Am I right?
Thanks for any comments.
Upvotes: 1
Views: 237
Reputation: 3978
For the copy semantic I usually follow these rules:
1) if my class is a POD I can use the compiler generated copy constructor and assignment operator.
2) if I want to prevent copies of my object, I declare copy constructor and assignment operator private and I don't implement them
3) if my class is not a POD I provide my implementation of copy constructor and assignment operator that provide a deep copy of the object. When an object has const data members I declare the assignment operator private and I don't implement it.
Upvotes: 0
Reputation: 92321
Your CopyableDataClass
is like a value, similar to an int
. There is nothing much to gain from allocating it dynamically, just like you generally don't do that with single int
s.
If your Domain
class contains just "copyable data" it will be just as copyable as its content.
Upvotes: 2
Reputation: 18218
Your user class should look like that:
class user
{
public:
// we can't construct a domain-user without knowing it's domain
user(Domain* domain) : m_domain(domain) { }
// return the domain the user is part of
Domain& get_domain() { return *this->m_domain; }
private:
// you can't copy a domain-user
user(user const&);
user& operator=(user const&);
Domain* m_domain;
};
Upvotes: 0