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

Join 136,562 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,895 people online right now. Registration is fast and FREE... Join Now!




Composition

 
Reply to this topicStart new topic

Composition

chronoTrigger
7 May, 2008 - 09:41 AM
Post #1

New D.I.C Head
*

Joined: 8 Oct, 2007
Posts: 43


My Contributions
I would like to know how do I pass data into the composition class through constructor.

For example I have two classes.

CODE

class myFile
{
public:
myFile(string fName);


private:
string fileName;

};


class student
{
public:
student(string name, string fName);

private:
string studentName;
myFile writeToFile;
}



In my main function when the constructor is called it will pass student name and file name and also I would like the file name will be passed to myFile class constructor.

how can I do that?

thanks


User is offlineProfile CardPM
+Quote Post

skaoth
RE: Composition
7 May, 2008 - 10:38 AM
Post #2

D.I.C Regular
Group Icon

Joined: 7 Nov, 2007
Posts: 343



Thanked: 10 times
Dream Kudos: 100
My Contributions
What you are trying to do is commonly referred to as constructor initialization.
When an object is created, the constructor of class allows you to initialize your class before the actual object is technically created.

This is how you would do this

CODE

class student
{
    public:
        student(string name, string fName) : writeToFile(fName)
        {
            ....
        }
};

User is online!Profile CardPM
+Quote Post

chronoTrigger
RE: Composition
7 May, 2008 - 12:21 PM
Post #3

New D.I.C Head
*

Joined: 8 Oct, 2007
Posts: 43


My Contributions
thanks for your reply, and I tried like you suggested, but it gives error though. It's saying WroteToFile is not a base or member. This error message maybe it assumes that I'm calling my base class constructor using inheritance, but I don't use inheritnance.

But I found a solution to it though, but not sure if it's correct or not. Inside my student constructor, I just allocate new memory using the keyword new of myFile type.

CODE

student::student(string name, string fName)
{
    name = "\0";
    myFile newFile = new myFile(fName);

}



}
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 11:40PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month