CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: operator+

  1. #1
    Join Date
    May 2018
    Posts
    158

    operator+

    Code:
    class vector{
      int *vett;
      long dim;
    public:
      vector(int);
      operator int()const;
      ~ vector(){ delete[]vett; };
    };
    
    vector::operator int()const{
      int n = 0;
      for (int i = 0; i < dim - 2; i++)
      if ((vett[i] > vett[i + 1]) && (vett[i + 1] < vett[i + 2]))
        n++;
      return n;
    }
    
    vector:: vector(int d){
      (d < 1) ? dim = 1 : dim = d;
      vett = new int[dim];
      for (int i = 0; i < dim; i++)
        vett[i] = 0;
    };
    
    
    int main()
    {
    ...
    
    cout << int(v)
    ...
    }

    I have problems to understand how It's defined operator int.

    1. int is user-defined by operator keyword , right?
    2. because is not specified return value in operator int function ? I'm expecting int as return value because function says return n
    3. in main I'm expecting something as v.int(); or It's the same thing?

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: operator+

    Code:
    vector::operator int()const{
    operator int is a casting operator that is called when the cast int is applied to class vector. No return type is specified as the type of the return (which is mandatory) is the same as the cast type.

    In main, int(v) will execute operator int on v as an int cast is applied to v. The rturn valus is then displayed using cout.

    In general operator <typename> () defines a function that is called when <typename> cast is applied to a class object. It is good practice to have these operators perform some expected logical operation for the specified type. The example in post #1 isn't particularly good in that respect as the result is not what would be expected from applying an int cast.

    NB It is bad practice to have a user-defined class with the same name as an stl class (vector in this case).
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    May 2018
    Posts
    158

    Re: operator+

    So every time It's requested to convert class object to different type e.g. int, long, char, ... It's necessary to create casting operator where its name is the same of converted data type as int, long, char.
    this casting function cannot be called by v.operatorint(); ?
    What means stl class ?

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: operator+

    So every time It's requested to convert class object to different type e.g. int, long, char, ... It's necessary to create casting operator where its name is the same of converted data type as int, long, char.
    Yes - if the 'conversion' is done as a cast. But remember the 'conversion' should be that reasonably expected from the type cast. Having an int cast that says sums a vector of ints is code-able but not reasonable for that underlying type. Also note that for user classes, you can create different constructors that take different types of arguments. So if you have a class myc1 and myc2, to convert from myc1 to myc2, either myc2 can have a constructor that takes as an argument myc1 or myc1 can have an operator myc2() to cast from myc1 to myc2. Which way(s) this is done depends upon how the class(s) are expected to be used and their relationship.

    If you want explicit conversions, then you can have a class member function (or even non-member functions) called what you want that returns a value of the required type. Examples of this are the to_string(xxx) set of functions for converting ints, doubles etc to a string type.

    For example, in c++17 there is string_view. You can convert a string object into a string-view object. This is now done by a cast on string, but it was originally proposed that string_view had a constructor that took a string object. It was changed because as string_view was considered 'lower' in the hierarchy, there was no reason why string_view had to know anything about string.

    STL stands for Standard Template Library and covers all of the c++ classes, algorithms etc etc - basically anything that is in the std:: namespace.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: operator+

    As 2kaud said, STL stands for Standard Template Library, and a lot of people still use it.
    However, if you check the official C++ standard document, the term STL is never mentioned.
    The name is a holdover from a long time ago. It only covered templated containers and templated algorithms.
    The modern C++ Standard Library contains much more than just containers and algorithms.
    I prefer not to use the term STL, and in fact, in my book I never use it, except in the introduction to explain why I don't use it.
    The proper term is "C++ Standard Library".
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  6. #6
    Join Date
    May 2018
    Posts
    158

    Re: operator+

    Quote Originally Posted by 2kaud View Post
    Code:
    vector::operator int()const{
    It is good practice to have these operators perform some expected logical operation for the specified type. The example in post #1
    isn't particularly good in that respect as the result is not what would be expected from applying an int cast.
    I'm not able to understand this point, It's possibile to make example? Thanks
    Another time exam exercise asked to implement this casting operator and this one was solution.

    It is bad practice to have a user-defined class with the same name as an stl class (vector in this case).
    Ok, I renamed class choosing any name but I have been unlucky! I don't know about vector.

  7. #7
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: operator+

    Quote Originally Posted by zio_mangrovia
    I'm not able to understand this point, It's possibile to make example? Thanks
    Another time exam exercise asked to implement this casting operator and this one was solution.
    It depends on what does "conversion to int" mean for your class. Once you can clearly define what it means for your class, you can then define it in code. Sometimes (or rather quite often) "conversion to int" doesn't make sense for the class, hence you should not define such a conversion function.

    Quote Originally Posted by zio_mangrovia
    Ok, I renamed class choosing any name but I have been unlucky! I don't know about vector.
    Yes, and unless you take pains to read up comprehensively on the standard library, you won't know every name that is in the std namespace. Honestly, I beg to differ: having a user-defined class (template) with the same name as a standard library class (template) is alright, if you define your class in your own namespace and are prudent in your use of using directives. Having such a user-defined name in the global namespace is asking for a name collision since it is so common to see using directives for the std namespace in examples that you almost certainly have it in your own code, and chances are so will those who use your class. Even without a name collision, it is also asking for confusion because at first glance readers would tend to think that it is that class (template) from the standard library. Putting it in your own namespace solves that, as namespaces are meant to do, but it doesn't avoid the potential for name collision in your own code if you have a using directive for the std namespace in the relevant code.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: operator+

    I'm not able to understand this point, It's possibile to make example? Thanks
    For a simple example consider

    Code:
    #include <iostream>
    using namespace std;
    
    class myc {
    public:
    	myc() {}
    	myc(int d) : data(d) {}
    
    	int get() const noexcept
    	{
    		return data;
    	}
    
    	void set(int d) noexcept
    	{
    		data = d;
    	}
    
    	operator int() const noexcept
    	{
    		return data;
    	}
    
    	int t2() const noexcept
    	{
    		return data * 2;
    	}
    	operator long int() const noexcept
    	{
    		return data * 3;
    	}
    
    private:
    	int data = 0;
    };
    
    int main()
    {
    	myc mc(56);
    
    	int a = mc.get();	// Explicit obtain data
    	int b = mc;		// Implicit using int cast to get data
    	int c = mc.t2();
    	long int d = mc;        // Implicit using long int cast to get data
    
    	cout << a << " " << b << " " << c << " " << d << endl;
    }
    which gives the output

    Code:
    56 56 112 168
    Here, get() and set() are the usual getters and setters and t2() returns the held value doubled, but in this example it makes sense to also implement a cast for an integer as the stored/returned value is an int. Which is what is used to obtain the value of b. However, for d it might have been expected that this would give the same result as for b. As cast to int gave 56 so cast to a long int should also give 56 - right? But in this example cast to a long int gives 168 - which is not probably what users of the class would expect. So when using type casts, the returned value should be what a user of the class might reasonably expect. If there is no reasonable expectation from a type cast on a class (such as a type int for a vector class), then don't provide one. Provide a function instead.
    Last edited by 2kaud; June 15th, 2018 at 06:33 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: operator+

    Quote Originally Posted by Marc G View Post
    As 2kaud said, STL stands for Standard Template Library, and a lot of people still use it.
    However, if you check the official C++ standard document, the term STL is never mentioned.
    The name is a holdover from a long time ago. It only covered templated containers and templated algorithms.
    The modern C++ Standard Library contains much more than just containers and algorithms.
    I prefer not to use the term STL, and in fact, in my book I never use it, except in the introduction to explain why I don't use it.
    The proper term is "C++ Standard Library".
    Yes, but I think that the abbreviation STL is still very much used extensively. Even in Microsoft's compiler blogs

    "The STL will now detect some inputs to std::swap_ranges"
    "now activates the STL’s internal usage of “if constexpr”
    "use destructors rather than catch and reraise in more places in the STL"

    etc etc. See https://blogs.msdn.microsoft.com/vcb...he-c-standard/ and others.

    We'll just have to re-use the abbreviation of STL to mean STandard Library.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    Join Date
    May 2018
    Posts
    158

    Re: operator+

    all is clear

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured