Leave these fields empty (spam trap):
Name
You can leave this blank to post anonymously, or you can create a Tripcode by using the format Name#Password
Comment
[i]Italic Text[/i]
[b]Bold Text[/b]
[spoiler]Spoiler Text[/spoiler]
>Highlight/Quote Text
[pre]Preformatted & Monospace Text[/pre]
[super]Superset Text[/super]
[sub]Subset Text[/sub]
1. Numbered lists become ordered lists
* Bulleted lists become unordered lists
File

Sandwich


Discord Now Fully Linked With 420chan IRC

Somebody please explain interfaces in C++

Reply
- Thu, 22 Feb 2018 15:54:59 EST kBelsIZm No.37445
File: 1519332899121.jpg -(165557B / 161.68KB, 1280x960) Thumbnail displayed, click image for full size. Somebody please explain interfaces in C++
I have a question.
I've done something similar to the example on this page.
https://www.tutorialspoint.com/cplusplus/cpp_interfaces.htm

What they've got there is a virtual class that's called Shape. And then a load of derived classes called things like Rectangle and Circle etc.

Then the go
Rectangle rectangle = new Rectangle();

What I can't see is a way to declare a variable of type Shape. I don't care if that winds up a Rectangle or Circle because they both will implement the interface. How can I do the following?

Shape shape = methodThatWillGiveMeRectOrCircle();

My compiler can't compile that method. It says:
> error: return type 'Shape' is an abstract class
>>
Jarvis Wesslelure - Thu, 22 Feb 2018 23:07:30 EST 8hwK1pxu No.37447 Reply
>>37445
You have to use pointers.
Shape* shape = methodThatWillGiveMeRectOrCircle();
cout << "Totalarea: " << shape->getArea() << endl;
delete shape;
>>
Martha Drellyway - Fri, 23 Feb 2018 04:51:38 EST kBelsIZm No.37448 Reply
>>37447
That did the trick, thanks for pointing that out.
Can you explain to me why a pointer works here?
From what I understand, an int* can't just be assigned to a char* or void* without being explicitly cast so why is this different?
>>
Rebecca Dumbleshit - Fri, 23 Feb 2018 23:50:53 EST 8hwK1pxu No.37450 Reply
>>37448
That's just how polymorphism in C++ works.

A Rectangle IS A Shape so it can always be safely cast implicitly.
While a Shape may not necessarily be a Rectangle so it has to be explicitly cast.
dynamic_cast<Rectangle*>(shape)
>>
Wesley Furringnet - Sat, 24 Feb 2018 01:37:47 EST BW3MomrQ No.37451 Reply
You might be able to use references here too, but if that works then it's only because references are just pointers with nice syntax under the hood.

Report Post
Reason
Note
Please be descriptive with report notes,
this helps staff resolve issues quicker.