![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 | |
|
Hobbyist Programmer
Join Date: Mar 2006
Location: Lebanon
Posts: 148
Rep Power: 3
![]() |
Multiple constructors
Im writing a class which i want to give 2 contructors, one constructor has input parameters and one doesnt. Is this the correct way of doing things.
I only recieve a warning: Quote:
thanks. |
|
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5
![]() |
I'm not sure when that occurs without seeing your code.
Here is an example of how it does work. #include <iostream>
#include <string>
using namespace std;
class Packet
{
private:
int packetID;
string packetName;
public:
Packet();
Packet(int);
Packet(int, string);
void PrintAttributes();
};
Packet::Packet()
{
packetID = 0;
packetName = "no name";
}
Packet::Packet(int id)
{
packetID = id;
packetName = "no name";
}
Packet::Packet(int id, string str)
{
packetID = id;
packetName = str;
}
void Packet::PrintAttributes()
{
cout << "PacketID = " << packetID << endl;
cout << "PacketName = " << packetName << endl << endl;
}
int main()
{
Packet packet1;
packet1.PrintAttributes();
Packet packet2(1);
packet2.PrintAttributes();
Packet packet3(2, "myPacket");
packet3.PrintAttributes();
return 0;
}
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for." -- Socrates |
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,260
Rep Power: 5
![]() |
Some compilers will complain about multiple default constructors (or ambiguous function calls) in a circumstance like;
class Something
{
public:
Something();
Something(int x = 0, int y = 0);
};It is more common for a compiler to complain when attempting to use the class in this case (as that's when the compiler realises there are two candidates that can be called), but some smarter (?) ones do actually complain when compiling the class declaration. Another possible cause of such a message is accidentally providing two constructors that take no arguments; class Something
{
public:
Something();
// and later
Something(); // Whoops!
}; |
|
|
|
|
|
#4 |
|
Hobbyist Programmer
Join Date: Mar 2006
Location: Lebanon
Posts: 148
Rep Power: 3
![]() |
Thanks for your help guys.
I recieved the warning because i defined the contructors inside the class. the warning no longer appeared when i only defined the contructors return type parameters in the class and wrote their implemented code outside. just like nnxion wrote it. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|