Class hierarchy

I have the following problem. I have an abstract class with a virtual function.
< class A{
public:
virtual double GetTotalPrice() = 0;
}; >

A derived class:

<class B : public A {
A (string st, int number, double num) : x(st), y(number), z(num) { }
double GetTotalPrice() //returns a quantity
{
...

} }; >

Another derived class:
<class C : public B {
C (double d, int i) : dd(d), ii(i) {}
double GetTotalPrice() //returns a quantity
{
...

} }; >

My task is to create a vector with pointers to class A instances and add 3 elements of class B and 3 elements of class C to it.

Here is how I created the vector:

vector<A*> it;

But I am not sure how to add items to it, especially of class C. Can somebody help me with that? I also need to call the virtual function GetTotalPrice() to all of those elements. How do I do that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>

struct A { virtual void who_is_it() const = 0 ; };

struct B : A { virtual void who_is_it() const override { std::cout << "B\n" ; } };

struct C : B { virtual void who_is_it() const override { std::cout << "C\n" ; } };

int main()
{
    B b1, b2, b3 ;
    C c1, c2, c3 ;

    // vector of raw (non-owning) pointers
    std::vector<A*> pointers { &b1, &c1, &b2, &c2, &b3, &c3 } ;

    // iterate through the vector, calling the virtual function 'who_is_it'
    for( auto ptr : pointers ) if(ptr) ptr->who_is_it() ;
}
Last edited on
Thank you. But class B and C have constructors with elements that need to be used in the function that is virtual.
Can I use this somehow ?
A.push_back(new B("DD-54", 3, , 7.50); or something similar.
> Can I use this somehow ?
> A.push_back(new B("DD-54", 3, 5, 7.50)); // ) added at the end

You can, but you do not need to, and you shouldn't.

For this exercise, this would suffice:
1
2
3
std::vector<A*> vec ;
B b_one("DD-54", 3,  5, 7.50);
vec.push_back( &b_one ) ; 
Last edited on
Thank you!So no need to create these pointers, right?
1
2
3
4
5
B b1, b2, b3 ;
    C c1, c2, c3 ;

    
    std::vector<A*> pointers { &b1, &c1, &b2, &c2, &b3, &c3 } ;
Last edited on
Thanks a lot!
It worked!
> So no need to create these pointers, right?

We are creating pointers alright, as anonymous prvalues.
When we apply the address of operator & to an object of type B, it yields a pointer.

For instance, with, say, B b1( "DD-54", 5, 7.50 ) ; &b1 yields a pointer of type B*
There is an implicit conversion from this pointer to a pointer of type A*, which is what the vector requires.
Topic archived. No new replies allowed.