C plus plus programming for deletion?
#include<iostream>
int main()
{
// Allocate some memory for an integer with value 42.
int* p=new int(42);
//
// do some stuff with integer...
//
// Release the memory.
delete(p);
// Nullify the pointer.
p=NULL;
}
Note that nullifying the pointer is not necessary when the pointer would fall from scope anyway (as in the above example), but it's good practice nonetheless. Consider the following:
#include<iostream>
int main()
{
int* p=new int;
std::cout<<"0x"<<std::hex<<p<<" = "<<std::dec<<*p<<std::endl;
delete(p);
std::cout<<"0x"<<std::hex<<p<<" = "<<std::dec<<*p<<std::endl;
}
When you run the above example, you will note that even though we didn't initialise or alter the integer, it still has a value (whatever happens to reside at the memory location at the time). So although the program runs, it may or may not produce the desired behaviour depending on the value of *p. In this case we don't actually care what the value is, so the program appears to run normally. But the program has undefined behaviour because the value of *p is not under our control once we delete the pointer.
If we nullify the pointer immediately after deleting it, the program will crash when we try to print the value of *p (an access violation will occur). While that is clearly undesirable, at least we immediately know we have a problem, and can alter the code accordingly:
int main()
{
int* p=new int;
std::cout<<"0x"<<std::hex<<p<<" = "<<std::dec<<*p<<std::endl;
delete(p);
p=NULL;
// p is still valid (with the value 0x00000000), but *p is not!
std::cout<<"0x"<<std::hex<<p<<std::endl;
}
What does try and finally mean in C plus plus programming?
State and explain any 4 predefined data types in C plus plus programming?
A char is always 1 byte long, but may be signed or unsigned depending on the implementation. Explicitly signed or unsigned char types are treated as being independent types from the implicit char type (3 separate types).
A short (or short int) is at least 2 bytes long while a long (or long int) is at least 4 bytes long. Both are implementation-dependent with regard their actual size and sign, but, like char, may be explicitly signed.
Char, short and long are used to store integers (whole numbers). A char can store signed values in the range -128 to +127, or unsigned values in the range 0 to 255.
A double is at least 8 bytes long while its shorter counterpart, a float, is at least 4 bytes long. Both are implicitly signed, floating point values.
To determine the length of any type (including predefined types) us the sizeof operator.
When you use Visual C plus plus which window do you use to change the attributes of a form?
There should be "Properties" window. If you do not see, you can make it visible if you go to "View"-> "Properties".
What is the C plus plus coding for implementation of queue using circular linked list?
The implementation is the same as that for a singly-linked list, the only difference being that rather than maintaining separate pointers to both the head and tail, you only need to maintain a pointer to the tail, since the tail's next node is always the head, which will be itself if there is only one node. As with all queues, insertions occur at the tail and extractions occur at the head.
Can include files be nested in c?
Yes, include files can be nested in C and C++. In fact, most library implementations do just that.
Is g plus plus similar to c plus plus?
G++ is the Gnu compiler's extension for C++. It is not a different language. It simply allows you to use the GCC compiler to write C++ code.
What is meant by heap in c or cpp?
If you see the word "heap" in the context of C/C++ programming, it is probably referring to one of two ideas.
First, if it is written as "the heap", it is probably referring to dynamically allocated memory. We conceptualize memory as either being on "the stack" or "the heap" in main memory. Memory allocation from the heap happens when a call to malloc (or similar functions) are called in C, or when the "new" operator is used in C++. This is in contrast to statically allocated memory, which comes from the load module and is known at compile-time, or from the "stack" which is used at run-time to allocate local scope, or automatic, memory.
Another usage of the word heap is a certain data structure called a heap. It is a very common data structure for priority queues and is crucial to the famous HeapSort algorithm. You can easily find more information on this data structure e.g. by searching for HeapSort.
/* C program to implement stack. Stack is a LIFO data strcuture LIFO - Last in First Out Perform PUSH(insert operation), POP(Delete operation) and Display stack */
#include
#include
#define MAXSIZE 5
struct stack /* Structure definition for stack */
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
/* Function declaration/Prototype*/
void push (void);
int pop(void);
void display (void);
void main ()
{
int choice;
int option = 1;
clrscr ();
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf ("--------------\n");
printf (" 1 -> PUSH \n");
printf (" 2 -> POP \n");
printf (" 3 -> DISPLAY \n");
printf (" 4 -> EXIT \n");
printf ("--------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/*Function to add an element to the stack*/
void push ()
{
int num;
if (s.top -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = s.top; i >= 0; i-)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}
by
ankit shukla
Program to find the occurrences of a given character in a string in c plus plus?
#include
#include
size_t count_char (const std::string& s, const char c)
{
size_t count = 0;
size_t offset = 0;
while ((offset = s.find(c, offset)) != s.npos)
{
++count;
++offset;
}
return count;
}
int main()
{
std::string str {"Hello world!"};
std::cout << "String: "" << str << """ << std::endl;
for (auto c : str )
{
size_t count = count_char (str, c);
std::cout << "'" << c << "' occurs " << count << " time" << (count==1?"":"s") << "." << std::endl;
}
}
Example output:
String: "Hello world!"
'H' occurs 1 time.
'e' occurs 1 time.
'l' occurs 3 times.
'l' occurs 3 times.
'o' occurs 2 times.
' ' occurs 1 time.
'w' occurs 1 time.
'o' occurs 2 times.
'r' occurs 1 time.
'l' occurs 3 times.
'd' occurs 1 time.
'!' occurs 1 time.
Real world is full of classes explain?
In the real world, we humans like to classify everything from living things to inanimate objects, grouping things by the properties they share. For instance, in the world of living things we classify everything by kingdom, phylum, class, infraclass, order, suborder, family, subfamily, tribe, subtribe, genus and species. Thus the homo sapiens species belongs to the kingdom of animals, the phylum of chordata, the class of mammals, the order of primates, the family of hominidae, the tribe of hominini and the genus homo. Each classification is a more specialised type than the one that precedes it. Thus higher classes are more generic and lower classes more specific. The bat, which is also in the class of mammals, shares the same phylum and kingdom as we do, but differs in its order, family, tribe and genus. Thus we are related to bats in as much as we are both a type of mammal.
This type of classification is known as a taxonomy, and can be represented as a hierarchy, a family tree structure, with the most generic class at the top, or root, and the more specialised types splitting off on each subsequent level.
Just as we classify objects in the real world, we classify objects in the virtual world using a virtual taxonomy. The virtual taxonomy need not accurately reflect any real world taxonomy of the objects we are representing. If we wished to model a dog kennel, then we can limit the taxonomy to the genus: canis. If we also wished to identify the individual species and breed of dog then we might include those more specialised classifications, or we may limit our classification to breed. The point is we need only include those aspects that are actually of relevance to our program. For instance, we don't really need to know that a dog is actually a class of mammal unless we wished to segregate mammals from other classes, such as reptiles, but group them as animals.
By organising objects in this manner, we can greatly reduce the amount of duplicate code we need to write simply by encapsulating the generic functionality within the upper base classes, and placing the more specific functionality within the lower derived classes. For instance, most animals make some sort of noise, thus every animal object can "speak". When we call that method upon a dog, we would expect it to bark, while a cat should meow. These are simply specialised methods of a common, generic method. Animals that don't make a noise can simply default to the generic animal method, which simply produces no sound. Thus we need only cater for those that do make a sound.
What does the capacity vector member function return and how should this be used?
The vector::capacity member function returns the capacity of the storage space currently allocated to the vector, in terms of elements. The capacity is not necessarily the same as the size of the vector, but it will always be equal to or greater than the size. You can specify the capacity by using the vector::reserve member function. Reserving space for elements allows the vector to insert new elements into the vector without the need to reallocate. However, the vector automatically reallocates whenever you add more elements than the current capacity allows, and may increase the capacity beyond the new size. To optimise the capacity at any time, use the vector::shrink_to_fit member function.
The following code demonstrates how size and capacity relate to each other:
#include
#include
std::ostream& operator<< (std::ostream& os, const std::vector
{
os<<"Size:\t\t"< "\nCapacity:\t"< std::endl; return(os); } int main() { std::cout<<"Initialising\n"< std::vector std::cout< std::cout<<"Insert 1 element\n"< v.push_back(0); std::cout< std::cout<<"Insert 99 elements\n"< for(size_t i=1; i<100; ++i) v.push_back(i); std::cout< std::cout<<"Reserve space for 200 elements\n"< v.reserve(200); std::cout< std::cout<<"Extract last 50 elements\n"< for(size_t i=0; i<50; ++i) v.pop_back(); std::cout< std::cout<<"Resize to 25 elements\n"< v.resize(25); std::cout< std::cout<<"Optimise\n"< v.shrink_to_fit(); std::cout< } Output Initialising Size: 0 Capacity: 0 Insert 1 element Size: 1 Capacity: 1 Insert 99 elements Size: 100 Capacity: 141 Reserve space for 200 elements Size: 100 Capacity: 200 Extract last 50 elements Size: 50 Capacity: 200 Resize to 25 elements Size: 25 Capacity: 200 Optimise Size: 25 Capacity: 25
Java program that will input 10 scores and output the highest and lowest score?
import javax.swing.JOptionPane; //marlonroxas
public class loop_exer2
{
public static void main(String agrs[])
{
String input;
int trial=10, sc=0, h=0, l=0, test=0;
System.out.print("Scores: ");
for (int ctr=1;ctr<=10;ctr++)
{
input=JOptionPane.showInputDialog("Enter the Scores ["+trial+"] trials ");
sc=Integer.valueOf(input);
System.out.print(sc+", ");
if(test==0){h=sc;l=sc;test=1;}
if(sc>h){h=sc;}
else if(sc<l){l=sc;}
}JOptionPane.showMessageDialog(null, "Highest Score is: "+h+
"\n\nLowest Score is: "+l);
System.out.println();
System.out.println("Highest Score: "+h);
System.out.println("Lowest Score: "+l);
}
}
Definition of class in c plus plus?
A constructor is a function defined in a class with the name same as the class name and is used to automatically initialized the class data members. It is never preceded by a return type not even void.
eg -
class abc
{
int a, b;
abc() //constructor
{
a=0;
b=0;
}
};
main()
{
abc a;
}
The time we create object of the class in the main function the data members of the class are automatically initialised.
Constructor can even take parameter. Those constructor are known as parameterised constructor.
Perform addition multiplication subtraction of 2-D array using Operator Overloading in C plus plus?
#include<iostream>
#include<vector>
#include<random>
template<const size_t R, const size_t C>
class Matrix
{
public:
using row_type = int[C];
private: // attributes
int m_data[R][C];
public: // construction/assignment
Matrix ();
Matrix (const Matrix& source);
Matrix (Matrix&& source);
Matrix& operator= (const Matrix<R,C>& source);
Matrix& operator= (Matrix<R,C>&& source);
~Matrix () {}
public: // accessors
row_type& row (const size_t index) { return m_data[index]; }
const row_type& row (const size_t index) const { return m_data[index]; }
row_type& operator[] (const size_t index) { return m_data[index]; }
const row_type& operator[] (const size_t index) const { return m_data[index]; }
size_t size() const { return R * C; }
size_t rows() const { return R; }
size_t cols() const { return C; }
public: // operations
Matrix<R,C>& operator+= (const Matrix<R,C>&);
Matrix<R,C>& operator-= (const Matrix<R,C>&);
};
template<const size_t R, const size_t C>
Matrix<R,C>::Matrix()
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] = 0;
}
template<const size_t R, const size_t C>
Matrix<R,C>::Matrix(const Matrix<R,C>& source)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] = source.m_data[row][col];
}
template<const size_t R, const size_t C>
Matrix<R,C>::Matrix(Matrix<R,C>&& source)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] = std::move (source.m_data[row][col]);
}
template<const size_t R, const size_t C>
Matrix<R,C>& Matrix<R,C>::operator= (const Matrix<R,C>& source)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] = source.m_data[row][col];
return *this;
}
template<const size_t R, const size_t C>
Matrix<R,C>& Matrix<R,C>::operator= (Matrix<R,C>&& source)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] = std::move (source.m_data[row][col]);
return *this;
}
template<const size_t R, const size_t C>
Matrix<R,C>& Matrix<R,C>::operator+= (const Matrix<R,C>& rhs)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] += rhs.m_data[row][col];
return *this;
}
template<const size_t R, const size_t C>
Matrix<R,C>& Matrix<R,C>::operator-= (const Matrix<R,C>& rhs)
{
for (size_t row=0; row<R; ++row)
for (size_t col=0; col<C; ++col)
m_data[row][col] -= rhs.m_data[row][col];
return *this;
}
template<const size_t R, const size_t C>
Matrix<R,C> operator+ (const Matrix<R,C>& lhs, const Matrix<R,C>& rhs)
{
Matrix<R,C> sum (lhs);
return sum += rhs;
}
template<const size_t R, const size_t C>
Matrix<R,C> operator- (const Matrix<R,C>& lhs, const Matrix<R,C>& rhs)
{
Matrix<R,C> sub (lhs);
return sub -= rhs;
}
template<const size_t R, const size_t C, const size_t R1, const size_t C1>
Matrix<R,C1> operator* (const Matrix<R,C>& lhs, const Matrix<R1,C1>& rhs)
{
static_assert (C==R1, "Matrix dimension mismatch!");
Matrix<R,C1> mul;
for (size_t x=0; x!=R; ++x)
{
for (size_t y=0; y!=C1; ++y)
{
int prod = 0;
for (size_t z=0; z!=C; ++z)
{
prod += lhs[x][z] * rhs[z][y];
}
mul[x][y] = prod;
}
}
return mul;
}
template<const size_t R, const size_t C>
std::ostream& operator<< (std::ostream& os, const Matrix<R,C>& m)
{
for (size_t row=0; row<R; ++row)
{
for (size_t col=0; col<C; ++col)
{
std::cout << m[row][col] << '\t';
}
std::cout << std::endl;
}
return os;
}
int main()
{
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution (1,9);
const size_t rows = 2;
const size_t cols = 3;
Matrix<rows, cols> a, b;
for (size_t row=0; row<rows; ++row)
{
for (size_t col=0; col<cols; ++col)
{
a[row][col] = distribution (generator);
b[row][col] = distribution (generator);
}
}
std::cout << "Matrix a:\n\n" << a << '\n' << std::endl;
std::cout << "Matrix b:\n\n" << b << '\n' << std::endl;
std::cout << "Matrix a + b:\n\n" << a + b << '\n' << std::endl;
std::cout << "Matrix a - b:\n\n" << a - b << '\n' << std::endl;
Matrix<cols, rows> c;
for (size_t row=0; row<rows; ++row)
{
for (size_t col=0; col<cols; ++col)
{
c[col][row] = distribution (generator);
}
}
std::cout << "Matrix c:\n\n" << c << '\n' << std::endl;
std::cout << "Matrix a * c:\n\n" << a * c << '\n' << std::endl;
}
What are C Plus Plus stream classes?
A stream class is a class that encapsulates a character buffer and allows simple insertion or extraction of character sequences from or to the buffer. A character sequence may be a single character or a string of characters. The stream may be associated with a device such as a keyboard (for extraction), a display (for insertion), a storage device such as a disk file (for either extraction or insertion, or both), or some other device that can process character sequences. The stringstream class has no device associated with it; it merely provides a character buffer for insertion or extraction from memory.
Any object that can be converted to a character sequence can be inserted into an output stream object, either by using the object's insertion operator (<<) or via one of the put() member methods associated with the stream. The standard library's output stream insertion operators provide overloads for all the built-in data types; char, int, float, double and pointer types, including all their modified types (signed, unsigned, long and short) as well as their aliases such as size_t. All the standard library <string> types are supported by all standard library streams, as are C-style strings. The insertion operator can also be overloaded to cater for all user-defined types that require it. C-style arrays and STL containers are not supported, however you can manually iterate through a sequence and insert the individual elements in an output stream, provided those element types have an appropriate insertion operator overload associated with them.
Character sequences can be extracted from an input stream using the stream's extraction operator (>>). As with output streams, the extraction operator is overloaded to cater for all built-in types, C-style strings and <string> types and can be overloaded to cater for user-defined types. When extracting a character sequence, all whitespace characters are ignored but are used to delimit each individual sequence. The stream's get() methods can be used to extract strings of arbitrary length (including whitespace) as well as use delimiters other than whitespace.
Never assume that a numeric value extracted from a stream can be converted to a valid value. Always extract to a string first, then perform the conversion to a numeric value. A common technique is to extract a string from the stream, then insert the string into a temporary stringstream object and finally extract from the stringstream to the numeric type. If the final extraction fails then the input string was not numeric. The stringstream will evaluate false (its fail bit will be set) but the original stream remains valid because extracting a string (even an empty string) is always a valid operation.
Both input and output streams use bit flags to determine their state. For instance, if you attempt to extract beyond the end of a stream associated with an input file, the eof bit is set. Note that reading the final sequence does not set the bit -- it is only set when you attempt to read another (non-existent) sequence. When a stream is used in a boolean expression, these flags are used to determine how the object is evaluated. If no flags are set, the object evaluates true, meaning the object is still in a valid state. If the return value is false, you can test individual flags to determine the state.
The following code snippet demonstrates both insertion and extraction from the standard I/O streams plus how to test for the successful extraction of an integer from the standard input stream (typically the keyboard) using a temporary stringstream:
int enter_integer (const std::string& prompt)
{
int i;
for (;;) // Forever loop -- repeat until input is successful.
{
// Temporary variables (on each iteration, these variables are created anew).
std::string input;
std::stringstream ss;
// Insert the given prompt to the standard output device.
std::cout << prompt;
// Extract input from the standard input device.
if (!(std::cin >> input))
{
// Input shouldn't fail, but if it does there's nothing we can do about it.
// Let the caller deal with it. See note below.
throw std::exception ("Unable to read from std::cin");
}
// Insert the temporary input string into the temporary stringstream object.
ss << input;
// Attempt extraction to an integer (returns true if successful)
if (ss >> i)
{
break; // Extraction successful, exit the loop.
}
// Extraction failed.
std::cerr << "Invalid input. Please re-enter.\n";
// The temporaries will fall from scope at this point,
// taking the bad input with them. The input stream
// remains valid for the next iteration.
}
return i;
}
Note: throwing an exception is never a good thing, but in this case it is the best option. If the exception is thrown, it means there's something seriously wrong with std::cin. Since that could affect the entire program, the best place to deal with this is in the program's main function, which should include a catch-all exception handler to handle any and all unhandled exceptions.
int main()
{
int num;
try
{
num = enter_integer ("Enter an integer: ");
}
catch (std::exception& e)
{
// Perform any necessary cleanup and log the error.
std::cerr << e.what() << std::endl;
return -1;
}
catch (...)
{
// Perform any necessary cleanup and log the error.
std::cerr << "An unknown exception occurred." << std::endl;
return -1;
}
// use num...
return 0;
}
What are the applications of polymorphism in c plus plus?
Polymorphism allows an object to assume different identities and behavior at run time. However, these objects should share similar features and inherit from a basic abstract object.
For example, we have a variety of graphics objects that are capable of drawing themselves, such as Circle, Triangle, Square, Rectangle and other shapes. A basic graphics object assumes the top of the inheritance hierarchy. Derived objects are the Circle, Triangle, Square, etc. The basic object supports a method called "Draw()" that allows it to draw itself on the screen. How this method is implemented is dependent on the actual object itself. Each derived object of the basic graphics object will have its unique implementation of Draw().
C++ has a feature called "dynamic binding" that implements polymorphism. Through dynamic binding, the appropriate virtual method() of Draw() is bound to the appropriate graphics object at run time.
A real world application such as a graphics editor maintains a container of objects that the user constructs at run time. Each of these objects is required to redraw itself on the screen when the screen refreshes and updates itself. Through polymorphism, the container of objects may iterate over itself and allow each object that it contains to dynamically draw itself at run time.
Sample code at compile time:
for (i=0; objects[i]; i++)
objects[i]->draw();
At run time, objects[0] = Circle, objects[1] = Square, objects[2] = Polygon, etc.
The behavior of the program at objects[i]->draw() is undefined until run time.
Other applications that utilize the feature of polymorphism includes:
How do you avoid garbage values in c plus plus programs?
Initialization. Hint: your compiler might warn you, neverignore warnings if you aren't absolutely sure what they mean.
What is meant by cascading in c plus plus?
Cascading refers to the following style of calling multiple methods in a sequence:
someObject.firstMethod().secondMethod().thirdMethod();
For this to work, firstMethod() returns an object on which secondMethod() is called, and similarly this returns an object on which thirdMethod() is called.
A commonly seen instance of this is the overloaded stream insertion operator - i.e. operator<<() - in the standard library. For example, you can write:
std::cout << "The meaning of life is " << 42 << std::endl;
Each invocation of operator<<() returns the std::cout object, allowing an arbitrarily long sequence of calls to be chained together.
Here's an example of a class which supports such cascading:
class MyClass {private:int data;
public:MyClass(int initData) : data(initData) {}
MyClass goUp() {data++;return *this;}
MyClass goDown() {data--;return *this;} };
With the above definition, we can write
MyClass obj;
obj.goUp().goUp().goDown();
and so on.
What is a statement used to open data file in c plus plus?
FILE* fopen(<filename>, <mode>);
E.g.,
FILE* f = fopen("C:\\Users\\<user_name>\\My Documents\\data_file.dat", "rb");
Opens the specified file for reading ("r") in binary mode ("b").
C plus plus program that display an employees name by entering an id?
Ideally you'd want to use a DBMS to store and retrieve the employee data, but we'll keep it simple and use some static data instead.
#include
#include
#include
#include
struct employee
{
std::string m_name;
unsigned m_id;
employee(std::string name, unsigned id): m_name(name), m_id(id) {}
};
std::vector
void load_data ()
{
employees.push_back (employee ("Alan", 1));
employees.push_back (employee ("Brian", 2));
employees.push_back (employee ("Charles", 3));
employees.push_back (employee ("David", 4));
employees.push_back (employee ("Eric", 5));
}
unsigned input_id (std::string prompt)
{
unsigned id = 0;
while (1)
{
std::cout< std::string input=""; getline (std::cin, input); std::stringstream ss (input); if (ss>>id) break; std::cout<<"Invalid input.\n"; } return (id); } employee* locate (unsigned id) { for (unsigned i=0; i { if (employees[i].m_id == id) return (&employees[i]); } return (NULL); } int main() { load_data (); unsigned id=0; do { if( id=input_id("Enter an employee ID (0 to exit)")) { if (employee* emp = locate( id )) std::cout< else std::cout<<"There is no employee with that ID.\n"< } } while( id ); std::cout< } Example output Enter an employee ID (0 to exit): 6 There is no employee with that ID. Enter an employee ID (0 to exit): 5 Eric Enter an employee ID (0 to exit): 2 Brian Enter an employee ID (0 to exit): 0
What is a function and its types in C plus plus?
A function is a procedure call; a re-usable block of one or more statements that can be called from any code that has access to it. Unlike a goto or a jump statement, functions automatically return to the caller when the function has completed its given task, just as if the code within the function were placed directly into your code (known as inline expansion). Functions are most useful whenever the same statements need to be called over and over from several places in your code, but without the need to duplicate that code (thus reducing maintenance costs). And since functions can call other functions, they can also be used to reduce highly complex functions into much smaller, easier to read functions.
Functions also differ from goto and jump statements in that they can be parametrised. That is, arguments can be passed to the function to alter its behaviour according to a given set of parameters. Moreover, functions can also return a value to the caller. The return value is often used to return an error code to indicate the success or failure of the function, but can also be used to return any one value. If more than one value must be returned, you can either return a complex object (a class, struct or union) or you can use output parameters (parameters may be used to provide input to a function, output from a function, or indeed both).
Parameters and argumentsWhen discussing functions, you will often encounter the terms parameters and arguments, often prefixed with the terms formal and actual. While many languages do not make any particular distinction between the terms, let's clarify exactly what these terms mean in the general sense.
An argument is an actual parameter or actual argument that is passed to a function from the calling code. In other words, it is the actual variable or constant that you pass into a function.
A parameter is a formal parameter or formal argument that always appears in a function's declaration and/or definition, and is used to accept the arguments passed to it. That is, the arguments are assigned to the parameters. Parameters are often declared but not named within function declarations, but they must be named in function definitions if the function's definition requires access to that parameter. Parameters that are declared but not named in a definition cannot be used by the definition, and are often called dummy parameters.
Function SignaturesThe name of a function and the parameters it accepts determine the function's signature. The function signature is used to disambiguate functions that have the same name but different parameters, known as function overloading. The return type of a function does not form any part of its signature, thus overloaded functions cannot differ by return type alone.
Types of FunctionsIn C++ there are essentially just two major types of function: external functions and member functions. A member function is also known as a method or member method, and is always declared to be a member of a class. Access to the method is determined by the class in which it is declared. External functions do not belong to any class and can be called from any function or class that has access to it.
Methods can also be classified by what they do. Accessor functions are used to retrieve information from the class while mutators manipulate the information within the class. Operators are methods that perform operations upon the information (such as assignment and equality). Operators can also be used to dynamically cast objects to different classes of object or even primitive data types. Special methods known as constructors initialise the class while a destructor cleans up the class when it falls from scope. Unlike other methods and functions, neither constructors nor destructors return any value, not even void. Methods can also be further classified as being non-virtual, virtual and pure-virtual in order to provide any combination of concrete and abstract interfaces to the class.
External functions usually provide auxiliary or utility functionality to a program. Such functions are usually miscellaneous in terms of their functionality and although some could be combined and classified to become member methods, the additional work required to design a class around them will often outweigh the usefulness in having the class. However, if the external functions require access to global data, it is better to combine those functions and the global data into a class, if only to eliminate the need for global data (which is generally a good thing).
C++ also includes many built-in functions made available though the standard library, including template classes and functions. Combined with user-defined classes and functions, these greatly reduce the need to design your own classes and functions entirely from scratch.