0

I am fairly new to object oriented programming, but have two simple questions on a piece of code. Note that this code has been simplified greatly without changing the net result:

#include <stdio.h>
#include <iostream.h>

class first_one
{
int x;
int y;
public: first_one()
{
  x = 1;
  y = 2;
}
};

class second_one
{
  int z;
  public: second_one()
{
  z = 3;
}

void print_it()
{
  printf("%d %d %d %d %d %d %d");
}
};

void main()
{
  first_one A;
  second_one B;
  B.print_it();
}

The following is printed:

-403 592 -221 3 2 1

Why does this occur?
Also, what C++ or object oriented principle did I violate?

3
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

Well you wanted C++ but you sort of mashed together non-OO C with OO C++. Also the .h antiquates the header and there is no real reason to have stdio.h in there since that is a C header. But if you are going to use printf the way you used it I'm surprised even compiles since you don't actually give printf any variables.

int x = 10;
printf("This is an integer: %i", x);

would print an integer

You should really just use cout if you are using C++

int x = 10;
cout<<"This is an integer: "<< x << endl;

is the C++ equivalent

0

>>I'm surprised even compiles
Depends on the compiler. Some compilers check the first argument to see if any other arguments are needed and give warnings for mismatches. Other compilers don't care.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.