Rocko'Steele
Rocko'Steele

Reputation: 69

passing a class as a parameter c++

Instead of doing this and keep on making redundant code for everything:

Molecule::Molecule(Hydrogenyx& h){
    //some code
}

Molecule::Molecule(Carbonyx& c){
    //same code as hydro
}

Molecule::Molecule(Sulphuryx& s){
    //same code
}

is there a way I can just make it so it can look like this?:

Molecule::Molecule(x){
    //code that can apply to all
}

Upvotes: 0

Views: 71

Answers (1)

R Sahu
R Sahu

Reputation: 206577

is there a way I can just make it so it can look like this?:

Sure. You can use a member function template.

Declaration:

template <typename T> Molecule(T& t);

Implementation:

template <typename T>
Molecule::Molecule(T& t){
   // The common code.
}

Upvotes: 2

Related Questions