Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need suggestion on constructors

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hello,
I would like to know how to setup a constructor correctly.
Is this how I set it up in a class struct?And what is a default constructor? CAn you show an example?

class blah
{
int A;
float B;
char C[30];
public:
The_Constructor(int,float,char);
void Read();
void Write();
};


The_Constructor::The_Constructor(int X,float y,char z[])
{
A=X;
B=y;
strcpy(C,z);
}

Please correct me if Im wrong. Am I doing it right?
thankx you.
 
You have the right idea. Although constructors always have the same name as the class. The header file for your class would look like this ->

#ifndef __BLAH_H__
#define __BLAH_H__

class blah {

private:

int A;
int B;
char C[30];

public:

blah( int x,int y,char z[] );//Constructor.
void Read();
void Write();

};

#endif

Notice how the constructor has the same name as the class.
And the implementation file would look like this ->

#include "blah.h"

blah::blah( int x,int y,char z[] ) {//Constructor.

//Init. attributes here, etc...

}

A default constructor is a constructor that takes no arguments. If you don't define a default constructor, the compiler will supply one for you. Also if you are just writting pure C++ code, you may want to stick with the C++ string class when working with strings. They are just more convient in my opinion. You don't have to call lib. functions to concatenate or copy char strings like you have to do with C style char strings. The C++ string class makes use of operator overloading. So concatenating two strings simply involves using the + operator, as using the assignment = operator will copy one string to another.




Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top