I'm stumped with a question. I wrote out an answer but it doesn't seem to be working. The inputs aren't the same as the outputs: it gives me some weird symbols for the name and 8 and 0 for the numbers.
1. You create two chaff objects stru1 and stru2 and read user input to assign values to the member variables.
1 2 3 4 5 6 7 8 9 10 11 12 13
chaff stru1;
chaff stru2;
std::cout << "Enter the name for the 1st dude: ";
std::cin.getline (stru1.dross, 20);
std::cout << "Enter his number: ";
std::cin >> stru1.slag;
std::cin.ignore (100, '\n');
std::cout << "Enter the name for the 2nd dude: ";
std::cin.getline (stru2.dross, 20);
std::cout << "Enter his number: ";
std::cin >> stru2.slag;
std::cin.ignore (100, '\n');
2. You create two chaff objects using placement new, but you never assign any values to the member variables so when you try to print them you get garbage.
1 2 3 4 5 6 7 8
char stru1mem [sizeof(chaff)];
char stru2mem [sizeof(chaff)];
chaff *stru1p = new (stru1mem) chaff;
chaff *stru2p = new (stru2mem) chaff;
std::cout << "1st dude's name: " << stru1p->dross << " and his number: " << stru1p->slag << std::endl;
std::cout << "2nd dude's name: " << stru2p->dross << " and his number: " << stru2p->slag << std::endl;
Using placement new with a old-fashioned struct is a bit pointless.
The mechanism is provided so you can invoke the constructor of your class independently of the memory allocation normally done by (regular, non-placement) new.
If you have no constructor there is zero point in using this approach.