Home > Net >  How to pass const struct pointer to a setter method in C
How to pass const struct pointer to a setter method in C

Time:09-17

I am trying to pass a const struct pointer to a setter setContainer of an auto-generated C API code so I can't change the class:

#include <iostream>
#include <memory>

class Class // Class definition
{
public:
    struct Container    // Container definition
    {
        double value = 0.0;
    };

    Class() { } // constructor
    ~Class() { } // destructor

    void setContainer(const Container * pContainer)
    {   
        mContainer = *pContainer; // setter
    }

    const Class::Container & getContainer() const
    {
        return mContainer; // getter
    }

private:
    Container mContainer;
};

As you can see I don't know how to pass the struct object to setContainer method in the correct manner. Smart pointers would be even better as I am using C 14.

int main()
{    
    Class objClass; 

    const auto container1 = objClass.getContainer();

    // Output: container1.value: 0.0
    std::cout << "container1.value: " << container1.value << std::endl; 
    
    // Need to set this at runtime
    Class::Container container2;
    container2.value = 5.0; 

    // Output: container2.value: 5.0
    std::cout << "container2.value: " << container2.value << std::endl; 
    
    // ERROR: no matching function for call to ‘Class::setContainer(Class::Container&)’
    objClass.setContainer(container2); 
    
    const auto container3 = objClass.getContainer();

    // Desired Output: container3.value: 5.0 (set by setContainer)
    std::cout << "container3.value: " << container3.value << std::endl; 

    return 0;
}

I'd really appreciate some help getting this right.

CodePudding user response:

Your setter function expects a pointer to a Container object, so give it one: just add the & operator to your argument:

    objClass.setContainer(&container2);

CodePudding user response:

you can use smart pointer and get() function to extract raw pointer as below

std::shared_ptr<Class::Container>m_container2 = std::make_shared<Class::Container>(container2);
 objClass.setContainer(m_container2.get()); 

or you can use & operator to get the pointer.

  • Related