Hi,

I've written a program that uses two objects that look like the ones below, and I was wondering why i would need an assignment operator and copy constructor for either of these classes. Are strings like char* (dynamic memory)? It would not be difficult to write these methods, I'm just wondering why? txs


Class A

class ClassA
{
    public:
        ClassA(string aString, ClassA* aLink):x(aString), link(aLink){}
        ClassA* getLink() const { return link;}
        string getString() const { return x;}

    private:
        string x;
        ClassA* link;
};

ClassB

const int SIZE = 1000;
class ClassB
{
    public:
        ///some methods to do various things
    private:
        ClassA* array[SIZE];
        int func1(string aString);
        ClassA* func2(ClassA* pointer, const string& aString);
};

Recommended Answers

All 4 Replies

the reason you would want to make your own is that with c++ the default will make an exact copy of the class and you will have two classes that point to the same memory address's. now if you delete the pointer in one class then the other class will be pointing to memory that you have no idea what could be in it. with variables that are not on the free store it doesn't matter really except for good programing practices but with free store information it is really a must.

You don't need a copy constructor for that. Only if you are using
dynamic memory, then you will need a copy constructor. The
std::string is it self dynamic and thus you don't have to keep
track of heap memory for it, the stl does it for you.

but he will need one for class ClassB because it has an array of ClassA objects

now if you delete the pointer in one class then the other class will be pointing to memory that you have no idea what could be in it.....

Thanks-thats a really good explanation. For some reason I was thinking that SomeClass* is different from char* aside from the fact that they are different types of pointers.

So I guess you need the Big 3 either when you allocate memory dynamically, or there are pointers involved?(are these the same things? I mean-pointers are always used in dynamic memory allocation, and memory pointed to by a pointer is always considered dynamic?) Memory pointed to by pointers isn't necessarily dynamic though is it? I guess they are two different things, but for both you need the Big 3. Maybe I'm wrong but i think i've got an idea of how it works now

txs for all these explanations :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.