ghostbody / 15-cpp-learning

15 c++ learning repository of SDCS SYSU
6 stars 3 forks source link

Use virtual or not in inheritance ? #10

Open DaddyTrap opened 8 years ago

DaddyTrap commented 8 years ago

A classmate asked me this question, but I don't have an answer...

In this week's assignment "(15 C++ Homework) D&A 5 Collection with Inheritance" In LinkedList.hpp:

class LinkedList : virtual public List {
    // ...
}

But in ArrayList.hpp:

class ArrayList : public List {
    // ...
}

In my opinion, I think using virtual in inheritance means I want to copy the base class only once when I use multiple inheritance. So, why ArrayList's declaration is different from LinkedList's here? Or, this is only a little mistake?

ghostbody commented 8 years ago

@DaddyTrap Just a mistake... you're right.

DaddyTrap commented 8 years ago

@ghostbody Well....Thank you all the same!

KatharinaLin commented 8 years ago

@ghostbody I don't know why vector is in this question...The question description is too long.I guess I may miss somthing important.But ......

KatharinaLin commented 8 years ago

16 04 21 1650_1 I remember that Fashi have ever said that when it refers to the pointer, it need to use deep copy.But +7 you ask me to use shadow copy..I'm confused.

DaddyTrap commented 8 years ago

@KatharinaLin In merge sort, if you use deep copy, for a 8-length linked list, it can create 2+4+8 = 14 copies and it waste many spaces.

Not ALL pointers should be deep copied. It depends. For example in this situation, it is no need to create new things because what we want to change is the list we sort.

In a word, if you don't want to change the data of the list, use deep copy. If you think changing the data is OK, then using shallow copy is OK, too.

Hope you can get some help here....

KatharinaLin commented 8 years ago

OK...I think it myself to understand.....thanks a lot

ghostbody commented 8 years ago

@KatharinaLin The question Collection is from the standard library of JAVA which is a programming language based at polymorphic. The ArrayList in java is similar to Vector in C++. However in Vector in java means thread-safe ArrayList.

So ArrayList in java and Vector in C++ are the same. They are all dynamic array implementation.

For merge sort, here is an example.

image

There is no need to have so many memory copies while you are doing merge sort in a list. So shadow copy or in other words, pointer operations should be applied instead.

Hope it can help you.

KatharinaLin commented 8 years ago

En ... Thank you.Get it!