constructor

Hi can someone explain the following script ?

#include<cmath>
#include<sstream>
#include<stdexcept>
using namepsace std;

namespace PPBOOK {

template<class S> class Price {
public :

Price(double p) : p_(p){check(p);}
Price(const Price<S>& p) : p_(p.p_){}
double price() const {return p_;}
Price<S>& operator=(double p)
{check(p); p_ = p; return *this;}
Price<S>& operator=(double Price<S>& p)
{p_ = p.p_; return *this}

private:
double p_;
static void check(double p) {
...........
}

};

What doest it mean "(const Price<S>& p)" and what does it mean p_(p.p_).

Why "Price<S>& p" I would immagine something like Price(const S& p).

Thank you in advace




These are called templates. They allow you to write a generic class or function that can do the same with with multiple types. Here's some reading for you:
http://cplusplus.com/doc/tutorial/templates/

It might be over your head - I don't know your current skill level. Let me know how you get on and feel free to ask for clarification of particular bits. :)

-Xander
From my point of view, templates is a good feature for generic programming but using it extensively in business-centric applications can "confuse" the developer doing maintenance. So I would tend to say employ templates more in coding for common used classes or so called libraries. For code that implement business logic they can do away with it. Only when it need to use then use the template syntax.

E.g
My own C++ program no template code but when I want to use C++ STL, I use the template to call them. This make the final C++ program more easily maintain-able.
Thank you Xander, I had already checked the tutorial, my question was regarding that sintax and what is the meaning.

Why "Price(const Price<S>& p)" i supposed something like Price(const S& p) and what it does

and

What is p_(p.p_) ?

I am a little confused

Thanks for helping me
Price(const Price<S>& p) is just a constructor, with the one argument (pointer)p. The statement after it is an Initializer, where p_(p.p_) means that you are setting variable'_p' to the value of data member _p in (pointer)p, which is the same as Price.p_ = p.p_

All constructers work like this:

1
2
3
4
5
6
7
8
9
10
11
class IsAClass
{
     int datamember1;
     char datamember2;
     const double datamember3;

     IsAClass(int a, char b, ect...) : datamember1(a), datamember2(b), datamember3(3.141)
           {
                  // ...
           }
}


That syntax after the arguments is the initializers. They initialize any data members you wish once the constructer is called, So if you declare a new instance of IsAClass using this constructor, datamember1 = a, datamember2 = b, and datamember3 = 3.141. This is the normal way of declaring constant data members, like datamember3.
Last edited on
Thank you very much Thatonedude, that really helped me.
Topic archived. No new replies allowed.