The following code is a toy example of what I can't figure out. I'd like to change a templated member of a templated member with a modifying member function but for some reason the modification doesn't work. Thanks for your help.
#include <iostream>
template< typename T >
class Node
{
public:
Node(){ this->val( T() ); }
Node( T value ){ this->val( value ); }
void val( T value ){ this->value = value;}
T val(){ returnthis->value; }
private:
T value;
};
int main( int argc, char **argv )
{
Node< Node<int> > node;
node.val().val( 10 );
// prints 0 (I'd like it to print 10):
std::cout << node.val().val() << std::endl;
node.val( Node<int>( 10 ) );
// now it prints 10:
std::cout << node.val().val() << std::endl;
// I'd like to use the modifier function rather than
// initialize a new instance if at all possible.
return 0;
}
In the list initializer you will get a warning . It should not cause trouble in most cases , but based on B.Stroustrup :
Here is something that never works: the {body} of a constructor (or a function called from the constructor) cannot get down to a derived class by calling a virtual member function that is overridden in the derived class. If your goal was to get to the overridden function in the derived class, you won’t get what you want. Note that you won’t get to the override in the derived class independent of how you call the virtual member function: explicitly using the this pointer (e.g., this->method()), implicitly using the this pointer (e.g., method()), or even calling some other function that calls the virtual member function on your this object. The bottom line is this: even if the caller is constructing an object of a derived class, during the constructor of the base class, your object is not yet of that derived class. You have been warned.
I'm glad you mentioned the this keyword, that's something that I've been thinking about. What naming convention do you recommend when I have three of the same variable:
1. Construction parameter,
2. get/set member function, and
3. member variable.
Also, is the this keyword also not recommended in non-constructor member functions. I've been using it in inherited classes. The Node<double>::value more than I'd like to type, if there's a better way.
1. As long as the parameters are too many.
2. Yes but not to all data members if possible. The concept is that an instance execute a task to another class or instance but does not give away all its implementation -> encapsulation.
3. Start data name with m_ should be fine.