A_Matar
A_Matar

Reputation: 2320

Cast an object to a data type?

How can I cast an object to a data type, say int / string? Following is an example code:

I want to be able to use the following add with integers and with var example var = <expression> + <expression> ; //expression can be int or var

Here is the code of var:

#pragma once
#include <string>

class vars
{
public:
    vars(std::string Name):name(Name){value = 0;}
    void setValue(int val);
    int getValue(void) const; 
//  std::string getName(void) const;
    ~vars(void);
private:
    std::string name;
    int value;
};

and here is the code of add:

#pragma once
#include "action.h"
#include "vars.h"

class add: public action
{
public:
    add(vars& v, int s1, int s2):target(v),source1(s1),source2(s2){} //downcast the vars to int if needed, how to do so explicitly?
    virtual void excute ();
    ~add(void);
private:
    vars& target; //not sure of it
    int source1, source2;
};

Upvotes: 0

Views: 95

Answers (1)

Otomo
Otomo

Reputation: 880

If you have got a contructor that takes exactly one parameter (in this case int) the type of the parameter can be converted implicitly to a temporary object of type vars. You then simply have to overload the operator+ for vars.

vars(int a); // Add this constructor
vars & operator+=(const vars other) {
    value += other.value; // Or some other operations
    return *this;
} // This as memberfuncion inside the vars class

vars operator+(vars left, const vars & right) {
    return left += right;
} // This outside the class

This is the straight forward solution.

It is better to define constructors with only one parameter as explicit to avoid unwanted implicit conversions. But if this is what you want you can go without it as well.

The other case in which you want to get an int (or some other type) as the result is solved by overloading the operatortype. For example:

explicit operator int() { return value; } // Inside class definition

// Which is called like:
vars var("meow");
auto sum = 1 + int(var); // The C-Style
auto sum = 1 + static_cast<int>(var); // The better C++ style

Again the explicit is optional but saver.

Upvotes: 1

Related Questions