constructor taking arguments

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ishekar

    constructor taking arguments

    Hi,

    I have a class which has only one constructor that takes an argument.
    I want the users of this class to pass the parameter in the declaration.
    The problem i am facing is this cannot be used in the declaration section.
    is there any work around.

    thanks
    ishekar.

    class A
    {
    public:
    A(string c){...};
    }

    //some user using this class
    class B
    {
    public:
    B();
    private:
    A("This is B's copy of A"); // this is not permitted
    }


  • Chris \( Val \)

    #2
    Re: constructor taking arguments


    "ishekar" <ishekara@vsnl. net> wrote in message news:bfg2a2$2tp $1@news.mch.sbs .de...
    | Hi,
    |
    | I have a class which has only one constructor that takes an argument.
    | I want the users of this class to pass the parameter in the declaration.
    | The problem i am facing is this cannot be used in the declaration section.
    | is there any work around.

    [snip]

    Yes, use an initialiser list:

    class A
    {
    public:
    A( std::string s ) : S( s ) {};
    private:
    std::string S;
    };

    class B
    {
    public:
    B( const std::string& S ) : AObj( S ) {}
    private:
    A AObj;
    };

    int main()
    {
    B BObj( "This is B's copy of A" );

    return 0;
    }

    Note: Although I have modified B's constructor, you
    need not have done it this way.

    Cheers.
    Chris Val


    Comment

    • ishekar

      #3
      Re: constructor taking arguments

      this works.

      thanks

      "Chris ( Val )" <chrisval@bigpo nd.com.au> wrote in message
      news:bfgfe7$egg 3k$1@ID-110726.news.uni-berlin.de...[color=blue]
      >
      > "ishekar" <ishekara@vsnl. net> wrote in message[/color]
      news:bfg2a2$2tp $1@news.mch.sbs .de...[color=blue]
      > | Hi,
      > |
      > | I have a class which has only one constructor that takes an argument.
      > | I want the users of this class to pass the parameter in the declaration.
      > | The problem i am facing is this cannot be used in the declaration[/color]
      section.[color=blue]
      > | is there any work around.
      >
      > [snip]
      >
      > Yes, use an initialiser list:
      >
      > class A
      > {
      > public:
      > A( std::string s ) : S( s ) {};
      > private:
      > std::string S;
      > };
      >
      > class B
      > {
      > public:
      > B( const std::string& S ) : AObj( S ) {}
      > private:
      > A AObj;
      > };
      >
      > int main()
      > {
      > B BObj( "This is B's copy of A" );
      >
      > return 0;
      > }
      >
      > Note: Although I have modified B's constructor, you
      > need not have done it this way.
      >
      > Cheers.
      > Chris Val
      >
      >[/color]


      Comment

      Working...