Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 109,554 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 1,330 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



constructor with a reference paramater

 
Reply to this topicStart new topic

constructor with a reference paramater

B.H.S.
post 6 Aug, 2008 - 11:19 PM
Post #1


New D.I.C Head

*
Joined: 4 Aug, 2008
Posts: 1

Hello,
If I need to have a constructor with a reference paramater. How should I write it?

class A{
A(float &, int); // my c'tor
};

I have to make sure that no one will write:
A(2.4,1);
or

...
double s = 3.0l;
A(s,1);
...

Thanks
Helen
User is offlineProfile CardPM

Go to the top of the page


KYA
post 7 Aug, 2008 - 07:35 AM
Post #2


#include <nerd.h>

Group Icon
Joined: 14 Sep, 2007
Posts: 2,932



Thanked 22 times

Dream Kudos: 1150
My Contributions


That's how i would write it. Outside the class you would have to have some sort of checking mechanism for the variable before you pass a reference of it to the class.

i.e.

cpp

//Reference.h file
#ifndef REFERENCE_H
#define REFERENCE_H

class Boy
{
public:
Boy(int&);//takes reference as parameter
~Boy();
int itsAge;
};

Boy::Boy(int& age)
{
itsAge = age;
}

Boy::~Boy()
{
}
#endif


And:

cpp

//main.cpp file
#include <iostream>
#include "Reference.h"
using namespace std;

int main()
{
//verify variable type or such here
int age = 5;
Boy theGuy(age);
cout << "The boy is: " << theGuy.itsAge << " years old!";
return 0;
}
User is offlineProfile CardPM

Go to the top of the page

Bench
post 7 Aug, 2008 - 11:01 AM
Post #3


D.I.C Addict

Group Icon
Joined: 20 Aug, 2007
Posts: 580



Thanked 4 times

Dream Kudos: 150

Expert In: C/C++

My Contributions


If you're writing a constructor which accepts arguments by-reference, then the safest way would be to pass by const reference, unless you need to modify the original variables.

cpp
class myclass
(
public:
myclass ( const int& , const double& );
);
The reason this is preferable, is to allow const variables to be passed to the constructor - the const qualifier provides the compiler a solid guarantee that the constructor cannot produce any modifying 'side effects' to the original variables, helping keep your code cleaner, and easier to follow.
User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 9/7/08 10:58PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month