I.T. Discussion Community!
-Collapse +Expand
C++
Search C++ Group:

Advanced
-Collapse +Expand C++ To/From
To/FromCODEGuides
-Collapse +Expand C++ Study Test
PRESTWOODCERTIFIED
-Collapse +Expand C++ Store
PRESTWOODSTORE

Prestwood eMagazine

August Edition
Subscribe now! It's Free!
Enter your email:

   ► KBC++ Knowledge Base  Print This    Code Snippet DB All Groups  

C++ Code Snippets Page

These Code Snippets are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the C++ sub-topics.

Contribute a Code Snippet
Expand All

57 C++ Code Snippets

Group: C++


Topic: C++

-Collapse +Expand 1. C++/CLI Empty String Check (String.IsNullOrEmpty)
 

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

String^ s;
  
//s = ""; //Uncomment to test 2nd case.
  
if (String::IsNullOrEmpty(s))
{
  MessageBox::Show("empty string");
}
Posted By Mike Prestwood, Post #102043, KB Topic: C++



Topic: C++ Language Basics

-Collapse +Expand 2. C++ Assignment (=)
 

C++ uses = for it's assignment operator.

int Age;
string FullName; //#include <string>
  
Age = 42;
FullName = "Randy Spitz";
Posted By Mike Prestwood, Post #101378, KB Topic: C++ Language Basics
-Collapse +Expand 3. C++ Case Sensitivity (Yes)
 

C++ is case sensitive. In C and C++ commands and variable names are case sensitive.

The following first standard C++ snippet works:

printf("hello\n");
 
Printf("hello\n"); //>>>Does not work!
Posted By Mike Prestwood, Post #101337, KB Topic: C++ Language Basics
-Collapse +Expand 4. C++ Code Blocks ({ })
 

For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

int Dog::Bark() {
cout << "My first class method!" << endl;
return 0;
};
Posted By Mike Prestwood, Post #101494, KB Topic: C++ Language Basics
-Collapse +Expand 5. C++ Comments (// or /* ... */)
 

Commenting Code
C++ uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
  
/*
* This is another popular
* way to write multi-line
* comments.
*/
Posted By Mike Prestwood, Post #101502, KB Topic: C++ Language Basics
-Collapse +Expand 6. C++ Comparison Operators (==, !=)
 

General Info: Round Floating Point Numbers

When comparing floating point numbers, make sure you round to an acceptable level of rounding for the type of application you are using.

Languages Focus: Comparison Operators

A comparison operator compares two values either literals as in "Hello" and 3 or variables as in X and Counter. Most languages use the same operators for comparing both numbers and strings. Perl, for example, uses separate sets of comparison operators for numbers and strings.

C++ Comparison Operators

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//C++Builder example (ShowMessage is a VCL method).
//Does C++Builder evaluate the math correctly? No!
If (.1 + .1 + .1 == .3)
ShowMessage("correct");
else
ShowMessage("not correct");
Posted By Mike Prestwood, Post #101812, KB Topic: C++ Language Basics
-Collapse +Expand 7. C++ Constants (const)
 

In standard C++, you use const and static const to declare constants.

//C++Builder 2009 Example:
const String kName = "Mike";
const int kAge = 35;
  
ShowMessage("Hi " + kName + ", you are " + kAge + ".");
Posted By Mike Prestwood, Post #101804, KB Topic: C++ Language Basics
-Collapse +Expand 8. C++ Custom Routines
 

C++ is a hybrid language and as such offers global functions and class methods. A function must come before it's usage or you can prototype the function.

void sayHello(string pName) {
cout << "Hello " + pName + "\n";
};
 
int add(int p1, int p2) {
int result;
 
  result = p1 + p2;
return result;
};
Posted By Mike Prestwood, Post #101632, KB Topic: C++ Language Basics
-Collapse +Expand 9. C++ Deployment Overview
 

You can use any of the many free and commercially available installation packages.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

C++Builder 2007 and 2009 are bundled with InstallAware Express CodeGear Edition installer.

Posted By Mike Prestwood, Post #101906, KB Topic: C++ Language Basics
-Collapse +Expand 10. C++ Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

C++ Development Tools

Many compilers and development tools are available. Common development tools include Microsoft Visual C++, CodeGear C++Builder, and Eclipse.

With Visual C++ you use Microsoft's C++ syntax variations based on standard C++ or Microsoft's new C++/CLI syntax standard.

With C++Builder, you code using standard C++ with early support for the upcoming C++0x standard and using the VCL/RTL libraries. The VCL/RTL libraries are in common with Delphi which is based on Object Pascal. Within a project, C++Builder can use both C++ units and Delphi units.

With most C++ tools, you can also use your favorite C and C++ libraries too.

Posted By Mike Prestwood, Post #101547, KB Topic: C++ Language Basics
-Collapse +Expand 11. C++ End of Statement (;)
 

C++ uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

printf("Hello1");
printf("Hello2");
  
printf("Hello3"); printf("Hello4");
  
printf
   ("Hello5");
Posted By Mike Prestwood, Post #101772, KB Topic: C++ Language Basics
-Collapse +Expand 12. C++ File Extensions (.CPP and .H)
 

Important standard C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:

Posted By Mike Prestwood, Post #101486, KB Topic: C++ Language Basics
-Collapse +Expand 13. C++ If Statement (if..else if..else)
 

Same as standard C.

//C++Builder example using the VCL ShowMessage.
int x;
  
x = 8;
  
if (x == 10) {
ShowMessage("x is 10.");
} else if (x < 10) {
ShowMessage("x is less than 10.");
} else {
ShowMessage("x must be greater than 10.");
}
Posted By Mike Prestwood, Post #101877, KB Topic: C++ Language Basics
-Collapse +Expand 14. C++ Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

printf("Hello\n");
printf("Hello \"Mike\".\n");
 
cout << "Hello" << endl;
cout << "Hello \"Mike\".\n";
Posted By Mike Prestwood, Post #101528, KB Topic: C++ Language Basics
-Collapse +Expand 15. C++ Logical Operators
 

C++ logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
Posted By Mike Prestwood, Post #101883, KB Topic: C++ Language Basics
-Collapse +Expand 16. C++ Overview and History
 

Language Overview: C++ is a hybrid traditional C and OOP language. You code either in a traditional approach using functions, procedures, and global data, or you code using an OOP approach, or a mixture of both.

Target Platforms: C++ is suitable for creating any type of native code applications for many different platforms. The focus of this information is on creating native code Win32 applications that run on Microsoft Windows.

Posted By Mike Prestwood, Post #101717, KB Topic: C++ Language Basics
-Collapse +Expand 17. C++ String Concatenation (+ or append)
 

The + operator can be used with any combination of C++ strings, C strings and characters.

string fullname;

fullname = "Mike ";
fullname.append("Prestwood");

cout << "Hello " + fullname + "." << endl;
Posted By Mike Prestwood, Post #101608, KB Topic: C++ Language Basics
-Collapse +Expand 18. C++ Unary Operators
 

An operation with only one operand (a single input) such as ++X and --Y.

Posted By Mike Prestwood, Post #101556, KB Topic: C++ Language Basics
-Collapse +Expand 19. C++ Variables (int x=0;)
 

Variable names are case sensitive. The fundamental variable types in C++ are char, short int, int, long int, bool, float, double, long double, and wchar_t. The integer data types char, short, long and int can be either signed or unsigned. Signed variables are positive and negative. Unsigned variables are positive only.

C++, Java, and C# all use C-like variable declaration.

int Age;
int Age = 43;
float a, b, c;
string FullName; //#include 
unsigned short int FamilyMemberCount;
Posted By Mike Prestwood, Post #101577, KB Topic: C++ Language Basics
-Collapse +Expand 20. C++/CLI Code Blocks ({ })
 

Same as standard C++. For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

int Dog::Bark() {
cout << "My first class method!" << endl;
return 0;
};
Posted By Mike Prestwood, Post #101781, KB Topic: C++ Language Basics
-Collapse +Expand 21. C++/CLI File Extensions (.CPP and .H)
 

The C++/CLI standard file extensions are the same as standard C++. Important C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:

Posted By Mike Prestwood, Post #101776, KB Topic: C++ Language Basics



Topic: Standard C++

-Collapse +Expand 22. C++ Exception Trapping (try/catch)
 

Languages Focus: Exception Trapping

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

C++ Exception Trapping

try {
  //Some code.
}
catch(AnError) {
  //Error code here.
}
Posted By Mike Prestwood, Post #101365, KB Topic: Standard C++
-Collapse +Expand 23. C++ Report Tools Overview
 

Use any report writer you are comfortable with. C++Builder 2009 comes bundled with Rave Reports and Crystal Reports remains popular for Visual C++.

Posted By Mike Prestwood, Post #101852, KB Topic: Standard C++



Topic: C++ Language Details

-Collapse +Expand 24. C++ Associative Array (map)
 

General Info: Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus: Associative Array

Associative arrays are also known as a dictionary or a hash table in other languages.

C++ Associative Array

map<string, int> mymap;
mymap.insert(AValuePair);
Posted By Mike Prestwood, Post #101514, KB Topic: C++ Language Details
-Collapse +Expand 25. C++ Inlining (inline)
 

Use the inline keyword to tell the compiler to inline a routine.

inline int add(int p1, int p2) {
int result;
 
  result = p1 + p2;
return result;
};
Posted By Mike Prestwood, Post #101864, KB Topic: C++ Language Details
-Collapse +Expand 26. C++ Overloading
 

C++ Overloading

  • Operator - Yes for C++, no for C. Almost all operators can be overloaded for user-defined types
  • Method -
Posted By Mike Prestwood, Post #101460, KB Topic: C++ Language Details
-Collapse +Expand 27. C++ Pointers
 

C++ uses both pointers and references. Use the * operator to declare a pointer and use the & operator to declare a reference.

Posted By Mike Prestwood, Post #101914, KB Topic: C++ Language Details



Topic: C++/CLI Language Basics

-Collapse +Expand 28. C++/CLI Assignment (=)
 

C++/CLI uses = for it's assignment operator.

int Age;
string FullName;
  
Age = 42;
FullName = "Randy Spitz";
Posted By Mike Prestwood, Post #101894, KB Topic: C++/CLI Language Basics
-Collapse +Expand 29. C++/CLI Case Sensitivity (Yes)
 

Same as standard C++. Both standard C++ and C++/CLI are case sensitive. In C and C++ commands and variable names are case sensitive.

The following first C++/CLI snippet works:

MessageBox::Show("Hello");
 
messagebox::SHOW("Hello"); //>>>Does not work!
Posted By Mike Prestwood, Post #101778, KB Topic: C++/CLI Language Basics
-Collapse +Expand 30. C++/CLI Code Blocks ({ })
 

Same as standard C++. For C++, Java, JavaScript, and PHP, I prefer to put the first { at the end of the first line of the code block as in the example above because I see more C++ formatted that way.

class Cyborg {
public: System::Void IntroduceYourself() {
MessageBox::Show("Hi");
}
};
Posted By Mike Prestwood, Post #101782, KB Topic: C++/CLI Language Basics
-Collapse +Expand 31. C++/CLI Comments (// or /* ... */)
 

Commenting Code
Same as standard C++. C++ uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
  
/*
* This is another popular
* way to write multi-line
* comments.
*/
Posted By Mike Prestwood, Post #101785, KB Topic: C++/CLI Language Basics
-Collapse +Expand 32. C++/CLI Comparison Operators (==, !=)
 

Same as standard C++.

//Does C++/CLI evaluate the math correctly? No!
if (0.1 + 0.1 + 0.1 == 0.3)
MessageBox::Show("correct");
else
MessageBox::Show("not correct");
Posted By Mike Prestwood, Post #101813, KB Topic: C++/CLI Language Basics
-Collapse +Expand 33. C++/CLI Constants (const or literal)
 

C++/CLI supports the const and static const keywords of standard C++ as well as the new literal keyword. A literal is equivalent to static const in standard C++ and Microsoft's documentation recommends to replace static const with the new literal keyword because a leteral is available in metadata; a static const variable is not available in metadata to other compilers.

You can use static const within the class declaration or locally within a method. However, literal is only valid in the class declaration section and const is only valid within a method.

//some method {
const String^ MyName = "John";
static const Int32 MyAge = 27;
//}
// public class SomeClass : public Object {
public:
  literal double Pi = 3.14159;
  literal String^ MyName = "Mike";
  static const Int32 MyAge = 35;
//...
Posted By Mike Prestwood, Post #101805, KB Topic: C++/CLI Language Basics
-Collapse +Expand 34. C++/CLI Deployment Overview
 

C++/CLI projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

To create a ClickOnce deploy package, search the internet for mage.exe and mageui.exe.

In addition, you can use any of the many free and commercially available installation packages.

Posted By Mike Prestwood, Post #101913, KB Topic: C++/CLI Language Basics
-Collapse +Expand 35. C++/CLI Development Tools
 

The only development tool I know that supports C++/CLI at this time is Visual Studio.Net. C++/CLI was introduced in VS.Net 2005 and continued in VS.Net 2008.

Posted By Mike Prestwood, Post #101775, KB Topic: C++/CLI Language Basics
-Collapse +Expand 36. C++/CLI End of Statement (;)
 

Same as standard C++. C++ uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

//.Net WinForms example.
//Add, using namespace System::Windows::Forms;
MessageBox::Show("Hello1");
MessageBox::Show("Hello2");
MessageBox::Show("Hello3");
   
MessageBox::Show("Hello4"); MessageBox::Show("Hello5"); 
  
MessageBox:: 
  Show 
    ("Hello6");
Posted By Mike Prestwood, Post #101786, KB Topic: C++/CLI Language Basics
-Collapse +Expand 37. C++/CLI File Extensions (.CPP and .H)
 

The C++/CLI standard file extensions are the same as standard C++. Important C++ file extensions:

  • .CPP = C++ Source file. Your startup source file will have a main() routine.
  • .C = C source file (sometimes used for C++ source files too).
  • .H = Header include file.

Some important Visual C++ file extensions:

Posted By Mike Prestwood, Post #101777, KB Topic: C++/CLI Language Basics
-Collapse +Expand 38. C++/CLI If Statement (if..else if..else)
 

Same as standard C.

int x;
  
x = 8;
  
if (x == 10) {
MessageBox::Show("x is 10");
} else if (x < 10) {
MessageBox::Show("x is less than 10");
} else {
MessageBox::Show("x must be greater than 10");
}
Posted By Mike Prestwood, Post #101872, KB Topic: C++/CLI Language Basics
-Collapse +Expand 39. C++/CLI Inlining (Automatic)
 

In C++/CLI, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

Posted By Mike Prestwood, Post #101860, KB Topic: C++/CLI Language Basics
-Collapse +Expand 40. C++/CLI Literals (qoute)
 

Same as standard C++. Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

MessageBox::Show("Hello");
MessageBox::Show("Hello \"Mike\".");
  
//Does ASP evaluate this simple
//floating point math correctly? No! 
if ((.1 + .1 + .1) == 0.3) {
MessageBox::Show("Correct");
} else {
MessageBox::Show("Not correct");
}
Posted By Mike Prestwood, Post #101788, KB Topic: C++/CLI Language Basics
-Collapse +Expand 41. C++/CLI Logical Operators
 

Same as C++ and Java. C# logical operators:

& and, as in this and that No Short Circuit
&& and, as in this and that short circuits
| or, as in this or that No Short Circuit
|| or, as in this or that short circuits
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
Posted By Mike Prestwood, Post #101919, KB Topic: C++/CLI Language Basics
-Collapse +Expand 42. C++/CLI Overview and History
 

Language Overview: A.k.a. C++.Net. Microsoft's C++ language for .Net Framework development.

Language History: C++/CLI was introducted with VS.Net 2005 and replaced Managed C++ (introduced with VS.Net 2002). C++/CLI was standardized by ECMA-372.

Target Platforms: C++/CLI is suitable for creating .Net Framework applications.

Posted By Mike Prestwood, Post #101773, KB Topic: C++/CLI Language Basics
-Collapse +Expand 43. C++/CLI String Concatenation (+)
 

C++/CLI performs implicit casting of numbers to strings. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

//Implicit casting of numbers.
//
//This fails:
//MessageBox::Show(3.3);
//
//This works:
MessageBox::Show("" + 3.3);
Posted By Mike Prestwood, Post #101922, KB Topic: C++/CLI Language Basics



Topic: C++ OOP

-Collapse +Expand 44. C++ Abstraction (=0 in a virtual method)
 

AbstractMemberFunction is a pure virtual function makes this class Abstract class indicated by the "=0"and NonAbstractMemberFunction1 is a virtual function.

class AbstractClass {
public:
virtual void AbstractMemberFunction() = 0;
  virtual void NonAbstractMemberFunction1();

};
Posted By Mike Prestwood, Post #101345, KB Topic: C++ OOP
-Collapse +Expand 45. C++ Class..Object (Yes)
 

Languages Focus: Class..Object

In short, a class is a data type, and an object is an instance of a class type. A class has methods (routines), properties (member variables), and a constructor. The current values of the properties is the current state of the object. The UML is one of the diagraming disciplines that allows you to document the various changing states of a series of objects.

C++ Class..Object

Posted By Mike Prestwood, Post #101400, KB Topic: C++ OOP
-Collapse +Expand 46. C++ Constructors (Use Class name)
 

A member function with the same name as the class.

class X {
public:
X(); // constructor for class X
};
Posted By Mike Prestwood, Post #101419, KB Topic: C++ OOP
-Collapse +Expand 47. C++ Destructor (~ClassName)
 

A member function with the same name as the class prefixed with a ~ (tilde). C++ destructors are automatically called when an object goes out of scope, or when you delete a dynamically allocated object. Every class can have only one destructor.

class Cyborg {
public:
// Constructor for class Cyborg
Cyborg();
  
// Destructor for class Cyborg
~Cyborg();
};
Posted By Mike Prestwood, Post #101430, KB Topic: C++ OOP
-Collapse +Expand 48. C++ Inheritance (: public ParentClass)
 

In C++ you use the class keyword to signify a class and a colon followed by the parent class name for inheritance.

In the following example, a terminator T-600 is-an android. 

class Android {
};
 
class T-600: Public Android {
};
Posted By Mike Prestwood, Post #101391, KB Topic: C++ OOP
-Collapse +Expand 49. C++ Inheritance-Multiple (Yes)
 

C++ supports both multiple implementation inheritance and multiple interface inheritance.

Posted By Mike Prestwood, Post #101445, KB Topic: C++ OOP
-Collapse +Expand 50. C++ Interfaces (No, but mimic it.)
 

You can mimic an interface by using a class that has only pure-virtual functions and no member variables.

Posted By Mike Prestwood, Post #101436, KB Topic: C++ OOP
-Collapse +Expand 51. C++ Member Visibility
 

C++ implements class and member visibility specifiers traditionally. Note the colon at the end of each visibility specifier and the semi-colon at the end of the class (the end of the statement).

class Cyborg: Public AParentClass {
public:
 
protected:
 
private:
};
Posted By Mike Prestwood, Post #101491, KB Topic: C++ OOP
-Collapse +Expand 52. C++ Prevent Derivation
 

Make the constructor a private member of the class.

Posted By Mike Prestwood, Post #101424, KB Topic: C++ OOP
-Collapse +Expand 53. C++ Static Members (static)
 

C++ supports static methods and static member fields using the static keyword.

class MyUtils {
public:
static void MyStaticMethod();
};
Posted By Mike Prestwood, Post #101479, KB Topic: C++ OOP



Topic: C++/CLI OOP

-Collapse +Expand 54. C++/CLI Base Class (System::Object)
 

In C++/CLI, the Object keyword is an alias for the base System::Object class and is the single base class all classes ultimately inherit from.

Posted By Mike Prestwood, Post #101779, KB Topic: C++/CLI OOP
-Collapse +Expand 55. C++/CLI Base Class (System::Object)
 

In C++/CLI, the Object keyword is an alias for the base System::Object class and is the single base class all classes ultimately inherit from.

Posted By Mike Prestwood, Post #101780, KB Topic: C++/CLI OOP
-Collapse +Expand 56. C++/CLI Finalizer (~ClassName)
 

Unlike standard C++, C++/CLI uses the .Net garbage collector to free managed object instances. Prism does not have nor need a true destructor.

In .Net, a finalizer is used to free non-managed objects such as a file or network resource. Because you don't know when the garbage collector will call your finalizer, Microsoft recommends you implement the IDisposable interface for non-managed resources and call it's Dispose() method at the appropriate time.

Posted By Mike Prestwood, Post #101847, KB Topic: C++/CLI OOP



Topic: C++/CLI WinForms

-Collapse +Expand 57. C++/CLI Report Tools Overview
 

Use any report writer you are comfortable with but Crystal Reports remains popular for Visual C++ and C++/CLI.

Posted By Mike Prestwood, Post #101853, KB Topic: C++/CLI WinForms
Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech