How can I achieve in c++, like

Foo foo = new Foo.SubFoo();
or
Foo foo = new Foo().SubFoo();

Where,
Foo : class
SubFoo: maybe sub class or independent class, but not method.

Note: i Don’t want to use "namespace"

class Foo {
  public:
    void SubFoo() { cout << "something"; }
};

int main() {
  Foo foo;
  foo.SubFoo();
}

edit: read the other part :x
you could do something like

class F { public: F() { cout << "something" << endl; } }
class Foo : public F { }

damn you daniweb, we can't delete posts? :(

class Foo {
  public:
    void SubFoo() { cout << "something"; }
};

int main() {
  Foo foo;
  foo.SubFoo();
}

edit: read the other part :x
you could do something like

class F { public: F() { cout << "something" << endl; } }
class Foo : public F { }

damn you daniweb, we can't delete posts? :(

at 13 and so quick !!!

but sorry SubFoo is NOT Method, it must be some class either subclass or independent one.

What do you expect it to do? Assign "foo" to the class that's in Foo, or call it's constructor (like I did in the second code example)?

ur 2nd example, not cleared to me, except inheritence.

what i need is,
the code must call SubFoo constructor, and return Foo object (by automatically cast)

I think what you mean is you want a wrapper class--

#include <iostream>
#include <cstdlib>

class SubFoo{
      
};

class Foo{
      
      private:
              SubFoo *sub;
      
      public:
             Foo(SubFoo &obj) : sub(&obj){}
             Foo(SubFoo *obj) : sub(obj){}
};

int main(){

   Foo foo = new SubFoo;
   
   SubFoo sb;
   
   Foo foo2 = sb;

   return 0;
}

Here's a modified version that uses SubFoo as an inner class (Most likely your original intent)--

#include <iostream>
#include <cstdlib>

//class SubFoo{
      
//};

class Foo{
      
      public:
             class SubFoo{
             };
      
      private:
              SubFoo *sub;
      
      public:
             
             
             
             
             Foo(SubFoo &obj) : sub(&obj){}
             Foo(SubFoo *obj) : sub(obj){}
};

int main(){

   Foo foo = new Foo::SubFoo;
   
   Foo::SubFoo sb;
   
   Foo foo2 = sb;

   return 0;
}

you could do it this way.

#include <iostream>

struct SubFoo ;

struct Foo
{
   Foo SubFoo() const ;
};

struct SubFoo : Foo
{
  SubFoo() { std::cout << "SubFoo constructor\n" ; }
} ;

Foo Foo::SubFoo() const { return ::SubFoo() ; }

int main()
{
  Foo foo = Foo().SubFoo();
}

but don't. it creates one of the worst kinds of cyclic dependencies- between a base class and a derived class.

Is this what you mean?

#include <iostream>
using namespace std;

class Foo
{
public:
      Foo()
      {
           cout << "Foo constructor\n";
      }
};

class SubFoo : public Foo
{
public:
      SubFoo()
      {
           cout << "SubFoo constructor\n";
      }
};

int main()
{
    Foo* myfoo = new SubFoo();
    
    return 0;
}

Foo foo = new Foo().SubFoo();
SubFoo: maybe sub class or independent class, but not method.

How could this ever be. SubFoo() is a function. Perhaps, it may be a default constructor, but that doesn't mean that it is not a function. A constructor is a special function that will called when a object is created.

The only other alternative I could think of is that subfoo() is a macro used in the worst possible way.
#define subfoo() something

what i need is,
the code must call SubFoo constructor, and return Foo object (by automatically cast)

Can a constuctor return a object?

Foo Foo::SubFoo() const { return ::SubFoo() ; }

Could you please explain me how the code calls SubFoo constructor.

My guess:
calling an object's constructor will create a temp object which will be destroyed immediately
and :: is used to instruct the compiler that you are not referring the fn SubFoo() of the base class.
Am I right?

CoolGamer48 : No, i didnt mean this.

Honestly if none of the above examples helped you at all, you need to be more descriptive.

Alex Edwards : i think, Description is enough. i am looking if there any clever coding/trick/design pattern exits to this in c++ ?

as we all know
1. constructor cant return.
2. one can not call constructor explicitily
3. dot (.) operator cannot be overloaded.

from above conditions, it seems impossible in c++,


but when i saw code like

Foo *foo = new Foo(new SubFoo());
some optimism appeared. here also "new subFoo() " return object ( may be Temp, not sure ) and passed to Foo Constructor as a parameter.

Alex Edwards : i think, Description is enough. i am looking if there any clever coding/trick/design pattern exits to this in c++ ?

as we all know
1. constructor cant return.
2. one can not call constructor explicitily
3. dot (.) operator cannot be overloaded.

from above conditions, it seems impossible in c++,


but when i saw code like

Foo *foo = new Foo(new SubFoo());
some optimism appeared. here also "new subFoo() " return object ( may be Temp, not sure ) and passed to Foo Constructor as a parameter.

I'm pretty sure Foo *foo = new SubFoo; is the closest you'll get since you are indeed upcasting a newly created derived type into type foo, and returning a type of Foo (although derived, it is still a type of Foo).

The only other way I can see this being done is by overloading the () operator to return a type of Foo and doing the cast (if any) there then (possibly) calling--

// untested - only because I doubt this is what you want and I doubt it works

// after overloading operator in Foo class to return a Foo type from SubFoo ref argument--

// Not sure what you're trying to accomplish that hasn't already been covered - oh well.

Foo foo = (*(new Foo))(*(new SubFoo));

Thanks Alex for ur kind help. After spending 1-2 weeks on this, i concluded that, you have to have to write code within the compiler limitation. you can't go beyond that.

"thinking out of box is my habbit, sometimes"

// Not sure what you're trying to accomplish that hasn't already been covered - oh well.
Foo foo = (*(new Foo))(*(new SubFoo));

i have to use this into my projects, i m working on. this will/should help our developers.

moreover may be i will send this as a suggestion to ISO C90 C Standard Library. may be in next version, they include (that constructor should return some thing, that we can use). ;)

Edited 3 Years Ago by mike_2000_17: Fixed formatting

@Prabakar

> Can a constuctor return a object?
> Foo Foo::SubFoo() const { return ::SubFoo() ; } > Could you please explain me how the code calls SubFoo constructor. ::subFoo() as an expression is evaluated to be an anonymous object of type ::SubFoo > My guess:
> calling an object's constructor will create a temp object

well, an an object's constructor cannot really be called

Constructors do not have names. ...
...
A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation will cause a constructor to be called to initialize an object. ...
...
A functional notation type conversion can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ...

ISO/IEC 14882(E) (12.1 - 1, 2, 13 )

> which will be destroyed immediately

after the initialization of the return value.

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object's initialization is complete. ...

- ISO/IEC 14882(E) 12.2 -4-
and a good compiler would use RV optimization to avoid the overhead of the creation and destruction of a temporary object.

> and :: is used to instruct the compiler that you are not referring the fn ...
> Am I right?

yes

@aecsant

> SubFoo : maybe sub class or independent class, but not method.

sorry, i missed that

> ...next version, they include (that constructor should return some thing, that we can use)

the reason that a constructor does not return some thing is that it is not a normal function.
a consequence of this:

The address of a constructor shall not be taken.

a function is an expression which has a type (perhaps void).
for example, std::rand() is an expression of type int.
a constructor is used as (part of a) definition. a definition has no type and therefore

No return type (not even void) shall be specified for a constructor. A return statement in the body of a constructor shall not specify a return value.

a trivial example:

int j ;
int i = j = 5 ; // ok,  j = 5 is an expression.

ink x = int y = 5 ; // error, int y = 5 is not an expression

> what i need is,
> the code must call SubFoo constructor, and return Foo object (by automatically cast)
> Foo foo = (*(new Foo))(*(new SubFoo)); > i have to use this into my projects,

would this not cause a leak?
and wouldn't either of these suffice for what you need?

Foo foo = SubFoo() ;
Foo* pfoo = new foo( SubFoo() ) ;

Thanks for your reply:)

I still don't understand 2 things. Please explain them too

1:

The address of a constructor shall not be taken.

- I am not getting it.
2:

would this not cause a leak?

- What is a leak? How is it caused by that code?

Thanks,

for clearing doubt about constructor, leak and other standards.

as of now, it seems not possible what i want. i have to change my design in c++.

Foo foo = SubFoo() ;
Foo* pfoo = new foo( SubFoo() ) ;

This doesnot solve any way.

> The address of a constructor shall not be taken.
> - I am not getting it.

perhaps this snippet will explain this (and a few other things about constructors):

namespace A
{
  enum COLOUR {} ;
  void foo( COLOUR ) {}
  struct bar { bar( COLOUR ) {} void function( COLOUR ) {} };
}

void fun1( A::COLOUR clr )
{ foo(clr) ; } // ok, function A::foo found via koenig lookup

void fun2( A::COLOUR clr )
{ bar(clr) ; } // error, A::bar found, but it is not a function

int main()
{
  A::COLOUR clr ;
  A::bar object( clr ) ;

  object.function( clr ) ; // ok, call function
  object.A::bar::function( clr ) ; // ok, call function

  object.bar( clr ) ; // error, invalid use of struct A::bar
  object.A::bar::bar( clr ) ; // error, invalid use of struct A::bar

  // ok, pointer to member function A::bar::function
  bool not_null = &A::bar::function ;

  // error, &A::bar::bar is not a legal expression
  // address of a constructor cannot be taken
  not_null = &A::bar::bar ;
}

> What is a leak? How is it caused by that code?
a leak is unintentional resource consumption by a program because the program fails to release resources when they are no longer needed. the most often talked about kind of leak is a memory leak; caused by an error in a program that prevents it from freeing up (dynamically allocated) memory that it no longer can use. Foo foo = (*(new Foo))(*(new SubFoo)); an anonymous object of type SubFoo is created using new, but delete is never called on the object. results in leak of any resource that would have been acquired by the object in SubFoo constructor and would have been released by SubFoo destructor. in addition to memory occupied by the object.

also, an anonymous object of type Foo is created using new, foo is copy constructed from it, and delete is never called on the object. the consequences are akin to that for the SubFoo object.

Comments
Thanks:)

Foo foo = (*(new Foo))(*(new SubFoo)); an anonymous object of type SubFoo is created using new, but delete is never called on the object. results in leak of any resource that would have been acquired by the object in SubFoo constructor and would have been released by SubFoo destructor. in addition to memory occupied by the object.

also, an anonymous object of type Foo is created using new, foo is copy constructed from it, and delete is never called on the object. the consequences are akin to that for the SubFoo object.

The above was not really recommended. I wanted to know exactly what the original poster wanted and threw that one out of my backside as a "guess" to see if it was remotely close, even after multiple attempts (by most of us) to answer his question didn't really get the cigar.

> ...threw that one out of my backside as a "guess" to see if it was remotely close,...
yes, that was apparent from your post.
i was alarmed when the original poster responded with:

i have to use this into my projects, i m working on. this will/should help our developers.

> ...threw that one out of my backside as a "guess" to see if it was remotely close,...

For the time being it closed.

i was alarmed when the original poster responded with:

Definitly, we will use the help, provided by you all, after carefull scanning.

These gave me the way, how to approach.

Thanks

@Vijayan

Sorry for not replying soon. I was out for a 4 day tour & only had time to enjoy. Thank you for posting. It is very helpful.

This article has been dead for over six months. Start a new discussion instead.