What is the difference between header files and namespace in cpp?
Header files are actual files - stored in the file system, referenced by file name, and #include'd in other files (at least, in C/C++ or other languages using the M4 macro preprocessor). Header files typically group pieces of code that are all interdependent parts of the same specific item together. For instance, a game might have a header file for all of its graphics rendering.
Namespaces, on the other hand, are an element of the programming language - they don't exist as a file system object, but rather as a designation within code telling the compiler that certain things are within that namespace. Namespaces typically group interfaces (functions, classes/structs, types) of similar (but not necessarily interdependent) items. For instance, the std namespace in C++ contains all of the Standard Library functions and classes.
In c plus plus ....Differences in passing primitive types and objects types?
Primitive types are usually passed be value (many professional programmers use reference or pointers). For object types is always used mechanism pass-by-reference because it allows to save a lot of memory by preventing coping data.
How do you make a message box in c plus plus?
#include<windows.h>
int main()
{
MessageBox(0,"Hello","Welcome Message",1);
return 0;
}
Using vector to add objects and display their member variables?
import java.util.Vector; suppose-:::: test t=new test(); /**this is how we add elements to vector*/ Vector v=new Vector(); v.addElements(t);
What is the C plus plus program to find the sum of elements above and below the diagonal?
In order to sum the elements above and below the diagonal, the array must be perfectly square. To guarantee the array is square we'll use a class template to implement an array of N arrays of length N. The following program demonstrates the minimal implementation required to sum the elements above and below the diagonal and will work for any array type for which operator+ is defined, which includes all the built-in numeric types such as int and double. operator<< has also been overloaded to assist in printing the array.
#include
#include
template
class square_array {
private:
std::array
public:
T sum_above (void) const;
T sum_below (void) const;
const std::array
std::array
};
template
T square_array
T sum = 0;
for (size_t row=0; row for (size_t col=row+1; col sum += data[row][col]; return sum; } template T square_array T sum = 0; for (size_t row=0; row for (size_t col=0; col sum += data[row][col]; return sum; } template std::ostream& operator<< (std::ostream& os, const square_array os << '{'; for (size_t row=0; row os << '{'; for (size_t col=0; col os << sa[row][col]; if (col } os << '}'; if (row } os << '}'; return os; } int main (void) { std::default_random_engine engine; std::uniform_int_distribution square_array // initialise elements with random values (range: 1 to 9) for (size_t row=0; row<5; ++row) for (size_t col=0; col<5; ++col) sa[row][col] = dist (engine); std::cout<<"Array = "< std::cout<<"Sum above: "< std::cout<<"Sum below: "< }
What is hard coded in c plus plus?
"Hard-coded" is a general term we use to mean constant as opposed to variable. Since all programs use constants to some degree, all programs can be regarded as being "hard-coded", thus the term is only meaningful within a given context. Typically, the term is used to indicate that some specific aspect of the code's data is programmer-defined rather than user-defined.
As an example, the value pi is a constant irrational value which means that we can only ever approximate its value. The value of pi has been calculated to over 10 trillion digits of precision, however 39 digits is more than enough to calculate the circumference of the universe to within 1 atom. Nuclear physicists rarely use more than 32 while NASA uses just 16 so it makes no sense to calculate pi to the nth degree of accuracy -- you can simply "hard-code" the exact precision you need using a constant.
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
// forward declarations
void sort(std::vector<int>&);
void sort(std::vector<std::string>&);
int main()
{
std::vector<int> int_array = { 7, 3, 8, 6, 2, 9, 1, 4, 0, 5};
std::vector<std::string> str_array = { "John", "Bill", "Alan", "Craig"};
sort (int_array);
sort (str_array);
}
void sort(std::vector<int>& arr)
{
std::sort (arr.begin(), arr.end());
}
void sort(std::vector<std::string>& arr)
{
std::sort (arr.begin(), arr.end());
}
Delegation and Containership in C plus plus?
Delegation and "containership" relate to embedding objects as opposed to employing inheritance. Both achieve the same thing in different ways but if a class is not intended to be used with inheritance (e.g., it has no virtual destructor), then embedding an object of the class is the only option.
When you embed an object you typically want to expose an interface to that object, but may not wish to expose the object's complete interface. In some cases you may wish to simplify the interface, in others you may wish to enhance it. This is achieved by declaring delegates, which are really nothing more than proxy functions that invoke the object's methods on your behalf, often simplifying the calls to those methods or enhancing them in some way. Delegates are essentially the embedded equivalent of overriding a base class virtual method.
For classes that cannot be inherited, embedding is the only option. However, once embedded, your new class can then be inherited. Thus embedding is often used to provide thin wrappers to enable inheritance. You cannot inherit from the embedded object, of course, but you can inherit from the thin wrapper, provide your thin wrapper includes a virtual destructor along with one or more virtual methods.
The STL containers are typical examples because they are not designed to be inherited from. Many see this as a bad thing, but it is actually a good thing. The STL is not a class hierarchy as such -- it is largely a framework of completely separate types, adaptors and algorithms that are "wired" together by iterators. It is not strictly object-oriented, but then object-oriented programming is not a magic bullet to every type of problem. The STL containers are designed to be both efficient and generic but are not intended to act as base classes. Although the STL could have provided thin wrappers for inheritance purposes, there are so many different ways to implement thin-wrappers that no single wrapper can ever cater for every programmer's needs. Thus it is left to the programmers themselves to create their own specific wrappers as and when they require them, including as much or as little generic behaviour as they need.
As an example, C++ does not include a generic "matrix" data type. Many other languages do, so it seems strange that C++ does not. However, those languages that do provide a matrix data type have to cater for everyone, and this inevitably leads to unavoidable inefficiencies. But with C++, you can simply implement your own to do exactly what you want as efficiently as possible using whatever combination of containers best suits your needs, with as much or as little generics as you required. C++ is nothing if not flexible.
Is the calendar in c plus plus programming array use?
You don't need an array to print a calendar. The following program shows how to print a calendar for any month from January 1900 onwards:
#include<iostream>
#include<iomanip>
#include<string>
#include<sstream>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::string;
using std::stringstream;
bool is_leap_year (size_t year)
{
if (year%4) return false;
if (year%100) return true;
if (year%400) return false;
return true;
}
size_t days_in_month (size_t month, size_t year)
{
switch (month)
{
case 4: case 9: case 6: case 11: return 30;
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 2: return is_leap_year (year) ? 28 : 29;
}
return 0; // error!
}
size_t day_of_year (size_t day, size_t month, size_t year)
{
size_t days = day;
while (--month)
days += days_in_month (month, year);
return days - 1;
}
size_t days_in_previous_years (size_t year)
{
size_t days = 0;
while (1900 < --year)
days += is_leap_year (year) ? 366 : 365;
return days;
};
size_t days_since_epoch (size_t day, size_t month, size_t year)
{
return days_in_previous_years(year) + day_of_year (day, month, year);
}
size_t day_of_week (size_t day, size_t month, size_t year)
{
return days_since_epoch (day, month, year) % 7 + 1;
}
void print_calendar (size_t month, size_t year)
{
switch (month)
{
case 1: cout << "January"; break;
case 2: cout << "February"; break;
case 3: cout << "March"; break;
case 4: cout << "April"; break;
case 5: cout << "May"; break;
case 6: cout << "June"; break;
case 7: cout << "July"; break;
case 8: cout << "August"; break;
case 9: cout << "September"; break;
case 10: cout << "October"; break;
case 11: cout << "November"; break;
case 12: cout << "December"; break;
default: return;
}
cout << ' ' << year << endl;
cout << "\n Su Mo Tu We Th Fr Sa\n";
size_t start_day = day_of_week (1, month, year);
size_t days = days_in_month (month, year);
size_t count = start_day % 7;
for (size_t i = 1; i <= count; i++)
cout << setw (4) << ' ';
for (size_t i = 1; i <= days; ++i)
{
cout << setw (4) << i;
++count;
if (count == 7)
{
cout << endl;
count = 0;
}
}
if (count)
cout << endl;
cout << endl;
}
size_t ask (string prompt)
{
for (;;)
{
cout << prompt;
string input;
cin >> input;
stringstream ss;
ss << input;
size_t reply;
if (ss >> reply)
return reply;
cout << "Invalid input.\n";
}
}
int main (void)
{
for (;;)
{
enter_month:
size_t month = ask ("Enter a month (1 - 12, 0 to exit): ");
if (!month)
break;
if (month > 12)
{
cout << "Invalid month." << endl;
goto enter_month;
}
enter_year:
size_t year = ask ("Enter a year (>= 1900, 0 to exit): ");
if (!year)
break;
if (year < 1900)
{
cout << "Invalid year." << endl;
goto enter_year;
}
print_calendar (month, year);
}
}
Why is ios a virtual base class?
There is no class named "ios" anywhere in the C++ standard library. <ios> is simply the header file. The actual class is called basic_ios and this serves as the base class for the basic_istream and basic_ostream classes (declared in <istream> and <ostream> respectively).
Although most streams are used for either input or output and therefore inherit from either basic_istream or basic_ostream, some streams are used for both input and output and therefore inherit both base classes. However, because both base classes share a common base class in basic_ios, the derived stream would inherit two instances of this class where only one is required. Thus basic_istream and basic_ostream both declare basic_ios as a virtual base class, thus ensuring the most-derived object in the hierarchy inherits just one instance of basic_ios.
What is the use of strcmp function in c plus plus?
strcmp is used to compare two strings. If the return value is zero, the two strings are the same. If the return value is less than 0, then the first string is less than the second string, otherwise the first string is greater than the second string. Strings are compared lexicographically, character by character.
C plus plus program to enter 1 01 101 0101?
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k=0,l;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
k++;
printf("%d ",k%2);
}
for(l=i;l<=4;l++)
{
k++;
}
printf("\n");
}
getch();
}
What Lead to C C plus plus and java?
(C and Lisp, ... data type") was adopted by many later languages, such as ALGOL 68 (1970), Java, and C#. ... C++ has a separate Boolean data type ( 'bool' ), but with automatic conversions from ... "Report on the Algorithmic Language ALGOL 68
Program to generate a multiplication table of 5 in Unix?
$vi multable.sh
n=5 i=1
for i in 1 2 3 4 5 6 7 8 9 10 11 12
do echo " $n * $i = `expr $n \* $i`" done
What is difference between C enum and C plus plus enum?
In C++, enum signifies a slightly stronger type than in C.
For example, in C, one could write:
enum Direction { UP, DOWN };
Direction d = 1;
In C++, this would be illegal, only UP or DOWN can be assigned to a variable of type Direction, though there is still implicit casting to integer, so one could still write:
int i = UP;
Another difference has to do with the way variable are declared in general in C++. In C, once the enum was declared as above, declaring variables of type Direction would have to be done through the enum keyword, like this:
enum Direction d = UP;
In C++, the name "Direction" becomes a type in itself, so you can write:
Direction d = UP;
How many types of user defined exceptions are there and list them?
They are user-defined. In other words: You & Me (Users) define them (make them). There is an endless number of user-defined exceptions
Who is the person behind c plus plus?
Bjarne Stroustrup (b.1950, Denmark) both designed and developed "C with Classes" in 1979. It was renamed "C++" in 1983 and the first commercial release was in 1985. He was chiefly responsible for the first implementation, but later concentrated on the language design and specification and sat on the C++ standards committee processing extension proposals. He also wrote the seminal book "The C++ Programming Language" (a must-have for any serious C++ programmer), which is now in its third edition. He is currently a Professor and holder of the College of Engineering Chair in Computer Science at Texas A&M University.
There are many high level languages What is the significance of another language C plus plus?
C++ was developed to address a deficiency in the Simula high-level language. Bjarne Stroustrup, the inventor of C++ found that while Simula's object-oriented nature allowed highly complex programs to be constructed more easily than with structured programming alone, it was far too slow for any practical purpose. Thus he set about converting C (which was not only fast but general purpose, portable and widely-used), to support object-oriented programming. Originally called C with Classes, C++ was released in 1983 and went on to become the most popular language of its kind. And while there are certainly other object-oriented languages that are much easier to work with than C++ (including Java, the most widely-used OOP language today), none can match C++ for its flexibility, efficiency and performance.
What is the algorithm for inserting values into a queue in c plus plus?
A queue usually infers first in first out (FIFO), therefore new values will need to be inserted after the last node (the tail node) and the queue must maintain pointers to both the head node for extraction and the tail node for insertion, and each node must maintain a pointer to the next node in the queue (singly-linked list).
The following code provides a bare-bones implementation of a singly-linked FIFO list, where each value is an integer. In real-life you'd use one of the built-in class templates, otherwise you'd have to re-write the same code to cater for all the different value types you might want to place in a queue (or create your own class template). However, the example serves to show the algorithm that is used to insert new values to the end of a queue. It does not show how to extract the first node from the queue.
#include <iostream>
using namespace std;
class Node
{
public:
Node( int iValue ):m_iValue( iValue ),m_pNext( NULL ){}
~Node(){ if( m_pNext ) delete m_pNext; }
Node * GetNext()const{ return m_pNext; }
void SetNext(Node * pNext ){ m_pNext = pNext; }
int GetValue()const{ return m_iValue; }
private:
Node * m_pNext;
int m_iValue;
};
class Queue
{
public:
Queue():m_pFirst(NULL),m_pLast(NULL){}
~Queue(){ if( m_pFirst ) delete m_pFirst; }
Node * GetFirst()const{ return m_pFirst; }
Node * GetLast()const{ return m_pLast; }
void Insert( int iValue );
void ShowAll()const;
private:
Node * m_pFirst;
Node * m_pLast;
};
void Queue::Insert( int iValue )
{
Node * pNew = new Node( iValue );
if( m_pLast )
m_pLast->SetNext( pNew );
else
m_pFirst = pNew;
m_pLast = pNew;
}
void Queue::ShowAll() const
{
Node * pNode = m_pFirst;
while( pNode )
{
cout << pNode->GetValue();
if( pNode != m_pLast )
cout << ", ";
pNode = pNode->GetNext();
}
cout << endl << endl;
}
int main()
{
Queue queue;
queue.Insert( 2 );
queue.Insert( 1 );
queue.Insert( 3 );
queue.ShowAll();
return( 0 );
}
#include <iostream>
#include <string>
std::string* concat_print_strings(std::string* pStr1, std::string* pStr2 )
{
std::string * strResult = new std::string( *pStr1 );
strResult->append( *pStr2 );
std::cout << strResult->c_str() << std::endl;
return( strResult ); }
int main()
{
std::string str1 = "This is a string.";
std::string str2 = " And this is another string.";
std::string* pStr = concat_print_strings( &str1, &str2 );
delete( pStr );
pStr = NULL;
return( 0 ); }
What is a special member function that constructs storage area for the data member of an object?
You are referring to class constructors however constructors are not functions of any kind; they have no return type (not even void), thus we cannot take the address of a constructor. Moreover, constructors do not actually construct the storage area; an object's memory is allocated automatically at the point the object is instantiated. Constructors are best thought of as being object initialisers, which is really the final part of the construction process.
Unlike ordinary functions, constructors also include an initialisation section which is executed implicitly even when no initialisation section is specified. The initialiser section is a list of constructors (technically, initialisers). If a non-static member or base class has no initialiser specified, that member or base is default constructed. The order of construction is always base before member (in the order specified by the class declaration). Once the initialisation section is complete, the constructor body executes. In most cases, constructor bodies are empty {} however we can use them to perform additional initialisation that cannot be easily performed by the initialisation section.
A pure virtual function is a virtual function that has?
A pure-virtual function is a function that must be overridden in derived classes. You simply add "=0" to the end of the function declaration.
class AbstractClass
{
public:
virtual void DoSomething()=0; // Pure-virtual.
};
How do you implement Pascal's Triangle in C plus plus?
There are many ways to implement Pascal's Triangle in C++. One of the easiest ways is to use a vector of vectors, which is essentially a two-dimensional dynamic array. Although you could use a static 2D array, the matrix would need to be sparse because the first row has only one value, while the second has two values, and so on. Unused elements would need to store the value zero, but unused elements are wasteful. You could improve upon this by creating a 1D array of dynamic arrays, however C++ vectors are much easier to work with and achieve the same thing.
The following program asks the user to enter the top value of the triangle and the number of rows in the triangle. The range of acceptable values has been limited to ensure all printed triangles will fit comfortably within an 80-character console window.
The program employs a simple class definition to encapsulate the triangle and its methods. The default constructor builds the triangle using the top value and the number of rows supplied from the user-input, while the print function displays the triangle's values in a symmetric triangle formation.
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<sstream>
// Some typdefs to simplify coding.
typedef unsigned int uint;
typedef std::vector<uint> row;
// Simple class definition.
class pascal_triangle
{
public:
pascal_triangle(uint top=1, uint rows=10);
void print();
private:
const uint get_width();
std::vector<row> m_triangle;
};
// Default constructor:
pascal_triangle::pascal_triangle(uint top, uint rows)
{
for(uint i=0;i<rows;++i)
{
row r;
uint x=top;
for(uint k=0;k<=i;++k)
{
r.push_back(x);
x=x*(i-k)/(k+1);
}
m_triangle.push_back(r);
}
}
// Return the width required for the largest value.
const uint pascal_triangle::get_width()
{
// Reference the last row of the triangle.
row& r=m_triangle[m_triangle.size()-1];
// Determine the largest value in that row.
uint largest=0;
for(uint i=0;i<r.size();++i)
if(r[i]>largest)
largest=r[i];
// Determine required width plus one space.
uint width=1;
do
{
largest/=10;
++width;
} while( largest );
// Return an even width.
return(width+width%2);
}
// Print the given triangle:
void pascal_triangle::print()
{
// Call private method to determine width.
const uint width=get_width();
// Repeat for each row...
for(uint i=0;i<m_triangle.size();++i)
{
// Insert half-width padding spaces.
std::cout<<std::setw((m_triangle.size()-i)*(width/2))<<' ';
// Print the row values.
row& r=m_triangle[i];
for(uint j=0;j<r.size();++j)
std::cout<<std::setw(width)<<r[j];
std::cout<<std::endl;
}
std::cout<<std::endl;
}
// Print the given range:
void print_range(const uint min,const uint max)
{
std::cout<<'['<<min<<".."<<max<<']';
}
// Return a natural number in the given range from user input:
uint enter_natural(const std::string& prompt,const uint min,const uint max)
{
uint result=0;
while(!result)
{
std::cout<<'\n'<<prompt<<' ';
print_range(min,max);
std::cout<<": ";
std::string in;
std::getline(std::cin,in);
std::stringstream(in)>>result;
if(result<minresult>max )
{
std::cout<<"The valid range is ";
print_range(min,max);
std::cout<<"\nPlease try again.\n"<<std::endl;
result=0;
}
}
std::cout<<std::endl;
return(result);
}
int main()
{
std::cout<<"Pascal's Triangle\n"<<std::endl;
uint top=enter_natural("Enter top value",1,10);
uint rows=enter_natural("Enter number of rows",2,10);
pascal_triangle t(top,rows);
t.print();
return(0);
}