Expression B b(A()) seemed no effect?

W

wij

Hi:
I encountered an expression B b(A()) which seemd to have no runtime
code compiled (as in the following example). Can anybody explain
this to me? Thank you.

// Build: g++ t.cpp (GCC version 3.4.2)
//
// [mypc]$./a.out
// strange?
// [mypc]$
//
#include <iostream>

class A {
public:
A() { std::cerr << "A ";
throw (const char*)"A_throw"; };
};

class B {
public:
B(const A&) { std::cerr << "B(A) "; };
};

int main(void)
{
try {
B b(A()); // constructing b object, no effect?
// expecting: "A_throw"
throw (const char*)"strange?";
}
catch(const char* str) {
std::cerr << str << '\n';
}
catch(...) {
std::cerr << "unknown\n";
};

return(0);
};
 
M

Markus Moll

Hi

Hi:
I encountered an expression B b(A()) which seemd to have no runtime
code compiled (as in the following example). Can anybody explain
this to me? Thank you.

B b(A());
is the declaration of a function b returning an object of type B and taking
a function as parameter.

A some_func();
B b(A());
B my_b = b(some_func);


Markus
 
J

John Carson

Hi:
I encountered an expression B b(A()) which seemd to have no runtime
code compiled (as in the following example). Can anybody explain
this to me? Thank you.

// Build: g++ t.cpp (GCC version 3.4.2)
//
// [mypc]$./a.out
// strange?
// [mypc]$
//
#include <iostream>

class A {
public:
A() { std::cerr << "A ";
throw (const char*)"A_throw"; };
};

class B {
public:
B(const A&) { std::cerr << "B(A) "; };
};

int main(void)
{
try {
B b(A()); // constructing b object, no effect?
// expecting: "A_throw"
throw (const char*)"strange?";
}
catch(const char* str) {
std::cerr << str << '\n';
}
catch(...) {
std::cerr << "unknown\n";
};

return(0);
};

Further to Markus's point, you can achieve your intended effect with:

B b = A();
 
B

benben

If a statement can be either parsed as function declaration or object
instantiation, the compiler will prefer the former.

ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top