Skip to content

C++ Classes

A minimal example of declaring a C++ class with public members and using an instance of it.

Published Dec 20, 1996

The bare minimum of C++ in a Win32 console program: define a class with a few public data members (int, char pointer, fixed array), declare one global instance of it, assign values to the members, and print them back out. It is a useful reference for the exact difference between defining a class and declaring an object of that class - the commented line shows the declaration syntax. Use it as a starting point when you are adding your first classes to an otherwise plain-C codebase.

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>


/* Create Class */
class ExampleCalss
{
public:
	int MyInt;
	char *MyChar;
	char MyArray[1024];
};

/* Declare Class */
/* class ClassName NameYouWantToCallIt; */
class ExampleCalss MyClass;

//////////////////////////////////////////////////////////////////////

int main()
{

	/* Assign Values To Class Values */
	MyClass.MyInt = 5;
	MyClass.MyChar = "Hello World";
	sprintf(MyClass.MyArray,"Hello Array");


	/* Print Values Of The Class Variables */
	printf("%d \n",MyClass.MyInt);
	printf("%s \n",MyClass.MyChar);
	printf("%s \n",MyClass.MyArray);

	return 0;
}

//////////////////////////////////////////////////////////////////////
An unhandled error has occurred. Reload 🗙