Home > other >  C Polymorphism: How to write function to accept any abstract class implementation
C Polymorphism: How to write function to accept any abstract class implementation

Time:02-01

I want to be able to pass whatever implementation of an abstract class into a function defined in a separate file, so that I can use the functionality for other projects and write the child class however it suits me.

main.cpp:

#include "my_process.h"


struct my_guy : V2 {

    my_guy(float x, float y)
        : V2(x, y) { }

    void double_me() override {
        x *= 2.f;
        y *= 2.f;
    }
};

int main() {
    process(my_guy(1.f,2.f));

    return 0;
}

my_process.h:

#pragma once

#include <iostream>

struct V2 {
    float x, y;

    V2(float x, float y) {
        this->x = x;
        this->y = y;
    }

    virtual void double_me() {  }
};

std::ostream& operator<<(std::ostream& output_stream, V2 vector) {
    output_stream << vector.x << ", " << vector.y;
    return output_stream;
}

void process(V2 vector) {
    vector.double_me();

    std::cout << vector << std::endl;
}

The above example prints 1,2 instead of the expected 2,4

CodePudding user response:

Your function process currently passes is parameter by value.

Because you currently pass by value, a new V2 value is created as the parameter, which will always have type V2 and act like a V2.

Change it to take a reference to whatever object is passed to it:

void process(V2 & vector)

Since the parameter is also modified, you will need to pass a named variable to convince the C compiler that you aren't accidentally modifying a temporary.

int main() {
    auto guy = my_guy(1.f,2.f);
    process(guy);
} 
  •  Tags:  
  • Related