Why do we need dynamic initialization of objects in C plus plus?
All objects must be initialised before we can use them. Initialisation can either occur statically (at compile-time) or dynamically (at runtime) however declaring an object static does not imply static initialisation.
Static initialisation relies on constant expressions. A constant expression is any expression that can be computed at compile-time. If a computation involves one or more function calls, those functions must be declared constant expression (constexpr) in order to take advantage of compile-time computation. However, whether or not the computation actually occurs at compile-time or not is implementation-defined. Consider the following code:
constexpr unsigned f (unsigned n) { return n<2?1:n*f(n-1); }
static unsigned num = f (4); // e.g., num = 4 * 3 * 2 * 1 = 24
int main () {
// ...
}
The above example is a potential candidate for compile-time computation. A good compiler will interpret this code as if it had been written:
static unsigned num = 24;
int main () {
// ...
}
However, if the function f () were not declared constexpr, the compiler would instead interpret the code as if it were actually written as follows:
unsigned f (unsigned n) { return n<2?1:n*f(n-1); }
static unsigned num; // uninitialised!
int main () {
num = f (4);
// ...
}
In other words, num is dynamically initialised -- at runtime.
Local objects are always initialised dynamically, as are objects allocated upon the heap (the free store). Static objects may be statically allocated, however this depends on the complexity of the object's constructor as well as the compiler's ability to perform compile-time computation.
What are the Advantages of in line function in c plus plus?
Inline functions effectively remove the function call altogether. However, just because a function is declared inline is no guarantee it will be inline expanded. it is merely a hint to the compiler that the function should considered for inline expansion, nothing more.
To understand how inline expansion helps, consider the following code:
void print(int x) {
std::cout << x << std::endl; }
int main()
{
int x=5;
print(x);
x*=3;
print(x);
print(++x);
return(0);
}
If the print() function could be inline expanded, it would be the same as if you'd written the following:
int main()
{
int x=5;
std::cout << x << std::endl;
x*=3;
std::cout << x << std::endl;
std::cout << ++x << std::endl;
return(0);
}
Our code may be a little larger, but it will execute that much faster because we've completely eliminated all three function calls. But while we could expand functions inline manually, as shown above, it makes no sense to do so. In a larger program where the function might be called several dozen times, it becomes that much harder to manage the inline code because there are so many instances of it. By keeping the function and declaring it inline, we can easily modify the function's behaviour because the code is all in one place. More fundamentally, however, if we manually expand functions inline, our code becomes that much larger, and performance is directly related to code size.
By giving the compiler hints as to which functions should be inline expanded, we allow the compiler to decide which is better in each case. The compiler uses complex algorithms to determine the best compromise between code size and performance. A function that is called many times but has little actual code is an ideal candidate for inline expansion, but then so is any function, regardless of complexity, that is called just the once. In the latter case the function may not be absolutely necessary, but functions can help make the code that uses them that little bit more readable and easier to understand, with much less need for commentary.
Even recursive functions can be inline expanded, but usually there is a limit to the depth of recursion (16 being a common limit). This can greatly increase the performance of the function at the expense of code size, which may affect other areas of the program. However, it is not something that should concern the programmer. The compiler is a better judge of what should be expanded and what should not. Even so, some compilers also include a non-standard force_inline flag that can override the compiler's decision, but this is best used sparingly, and only when the programmer is absolutely sure the performance gained will not cause problems elsewhere due to the increased code size.
static storage class in C tells that:
The variable will have the default value as zero.
The variable scope will be the file in which it is defined.
RaVi
What is the name of the function which violates the rules of Object Oriented Programming concept?
There is no such function. Some will say friend functions undermine encapsulation however this is errant nonsense. All members of a class are automatically friends of all instances of the same class, and yet no-one ever claims this to undermine encapsulation.
To quote Bjarne Stroustrup himself:
"Friend" is an explicit mechanism for granting access, just like membership. You cannot (in a standard conforming program) grant yourself access to a class without modifying its source. For example:
class X {
int i;
public:
void m(); // grant X::m() access
friend void f(X&); // grant f(X&) access
// ...
};
void X::m() { i++; /* X::m() can access X::i */ }
void f(X& x) { x.i++; /* f(X&) can access X::i */ }
How can you pass enum datatype as argument to function in c?
Here is the simple code, which demonstrates how you can use enum as function argument in c.
===================================================
#include <stdio.h>
// Enum declaration for power stat
enum PowerStat{ OFF, ON } powerStat; // Function printing the stat of power supply
void func( enum PowerStat ); int main(int argc, char* argv[])
{
// Set power supply stat OFF
powerStat = OFF;
// Call function to print the stat
func( powerStat);
// Set power supply stat ON
powerStat = ON;
// Call function to print the stat
func( powerStat);
return 0;
} void func( enum PowerStat stat)
{
printf("Power is = %s\n", stat ? "ON" : "OFF" );
} ==================================================
I haven't compiled and run above code but it has to work fine.
Let me know, if you found difficulty to compile it.
Email: ramji.jiyani@gmail.com
What does bind time have to do with recursion in C plus plus?
In C++, names are either statically bound at compile time, dynamically bound at runtime or (with compile time computation) not bound at all.
With respect to functions, dynamic binding only occurs when a function is invoked through a function pointer. This also applies to virtual functions because the virtual function table (vtable) is simply a list of function pointers that apply specifically to the runtime class of the object the function is invoked against. If we do not know the runtime type (the actual type) of an object at compile time, then we cannot statically bind a virtual function call at compile time. Instead, the compiler must generate code to perform a vtable lookup and then invoke the appropriate function dynamically. However, if the runtime type is known at compile time, then we can statically bind to a virtual function.
Static binding is faster than dynamic binding because we eliminate the indirection required to invoke a function via a pointer variable. Although we can write code to determine the runtime type of an object and thus statically bind all function calls, the overhead far outweighs the otherwise trivial cost of an indirection.
In the case of recursive functions, dynamic binding can only occur if we invoke the function through a function pointer. Once invoked, all recursive calls to that same function are statically bound:
unsigned object::fact (unsigned x) {
return x<2 ? 1 : x * (fact (x-1));
}
Here, the name fact used within the function is implicitly bound to this->fact and is therefore statically bound to object::fact. The initial invocation may or may not have been dynamically bound, but that has no bearing once the function is invoked.
If a function is declared constant expression (constexpr) and is used in a constant expression, the function call (and its binding) can be eliminated completely. Consider the following:
constexpr unsigned fact (const unsigned num) {
return num < 2 ? 1 : num * fact (num - 1);
}
void f () {
unsigned x = fact (7);
// ...
}
A good compiler will replace all of the above with the following:
void f () { unsigned x = 5040;
// ...
}
This is known as compile-time computation. We get the convenience of a function (even a recursive one) but with none of the runtime cost. And since the function is not required at runtime, there is nothing to bind to. However, constant expression functions are useful in that they can also be used in expressions that are not constant. For example:
void g (unsigned x) {
unsigned y = fact (x);
// ...
}
The above call to fact cannot be computed at compile time because x is not constant, so the compiler must statically bind the function instead. Thus we get the advantage of compile time computation when it is possible to do so and static binding when it is not.
If we wish to prevent static binding completely, then we need to use template metaprogramming instead:
template<unsigned N>
constexpr unsigned fact() {
return N * fact<N-1>();
}
template<>
constexpr unsigned fact<1>() {
return 1;
}
template<>
constexpr unsigned fact<0>() {
return 1;
}
Note that we must use specialisation to handle the end cases (where N is 0 or 1). It is not as elegant as the plain constexpr version, however it does guarantee that we only use compile time computation rather than static binding:
void h (unsigned x) {
unsigned y = fact<7>(); // OK: generates equivalent code to unsigned x = 5040;
unsigned z = fact<x>(); // error: x is not constexpr
// ...
}
How do you code fifo in c plus plus?
#include<iostream.h>
#include<conio.h>
#include<process.h>
#define SIZE 10
int queue[SIZE];
int front=-1,rear=-1;
void insert();
void del();
void display();
void main()
{
int ch;
do
{
clrscr();
cout<<"\nMAIN MENU."<<endl;
cout<<"\n1. Insert."<<endl;
cout<<"\n2. Delete."<<endl;
cout<<"\n3. Display."<<endl;
cout<<"\n4 Exit.\n"<<endl;
cout<<"\nEnter your choice.(1-4) : ";
cin>>ch;
switch(ch)
{
case 1 : insert();
break;
case 2 : del();
break;
case 3 : display();
break;
case 4 : exit(0);
default : cout<<"\nInvalid Choice.";
}
getch();
}
while(1);
}
void insert()
{
int val;
if(rear==SIZE-1)
{
cout<<"OVERFLOW."<<endl;
return;
}
cout<<"\nEnter the value : ";
cin>>val;
if(rear==front)
{
rear++;
front++;
queue[rear]=val;
}
else
{
rear++;
queue[rear]=val;
}
}
void del()
{
if(front==-1)
{
cout<<"\nQueue is empty.";
return;
}
if(front==rear)
front=rear=-1;
else
front++;
}
void display()
{
int front_vir=rear;
if(front==-1)
{
cout<<"\nQueue is empty.\n";
return;
}
while(front_vir<=rear)
{
cout<<queue[front_vir]<< " ";
front_vir++;
}
}
What is the program to find the area of polygons using c plus plus?
#include<iostream>
#include<vector>
#include<assert.h>
// Typdefs to hide unnecessary implementation detail and remove verbosity.
using Coordinates = std::pair<int,int>;
using Polygon = std::vector<Coordinates>;
// Calculate the area of a given polygon.
int area (const Polygon& polygon)
{
// The given polygon must list all vertices in the correct sequence
// either clockwise or anti-clockwise. It does not matter which
// vertex begins the sequence, but the last vertex is assumed to
// join the first.
// Initialise an accumulator.
int accumulator = 0;
// A polygon with less than 3 vertices is no polygon!
if (polygon.size() < 3)
return accumulator;
// The last vertex is the previous vertex to the first vertex.
// We'll deal with this specific pair of vertices first.
size_t previous = polygon.size() - 1;
// Iterate through all vertices in sequence.
for (size_t current=0; current<polygon.size(); ++current)
{
// The previous and current vertices form an edge. We need to calculate
// the area of the imaginary rectangle extending horizontally from this
// edge until it meets the Y-axis. This edge may not be vertical so we
// also extend in the opposite direction by the same amount. That is,
// for vertices {x1, y1} and {x2, y2}, the imaginary rectangle's opposing
// corners will be at imaginary vertices {0, y1}, {x1+x2, y2}. The area
// of this imaginary rectangle is therefore (x1+x2)*(y1-y2).
// Note: the imaginary rectangle's area may be negative but that's OK.
// It'll simply be subtracted from the accumulator and that's exactly
// what we want.
accumulator +=
(polygon[previous].first + polygon[current].first) *
(polygon[previous].second - polygon[current].second);
// The current vertex now becomes the previous vertex
// in readiness for the next iteration.
previous = current;
}
// Remove the sign (make absolute).
accumulator *= (accumulator<0) ? -1 : 1;
// At this point the accumulated total is guaranteed to be an even
// number (as we'll see). But let's play safe and assert that fact.
assert (accumulator % 2 == 0);
// Since each imaginary rectangle was exactly double what we needed
// (because we extended in both directions), divide the accumulated
// total by 2. It's more efficient to do that here, once, rather
// than for each individual rectangle. We don't have to worry about
// fractions since the accumulator is guaranteed to be even.
return accumulator / 2;
}
// Driver to test the function.
int main()
{
Polygon square;
square.push_back (Coordinates (0, 0));
square.push_back (Coordinates (0, 10));
square.push_back (Coordinates (10, 10));
square.push_back (Coordinates (10, 0));
assert (area (square) == 100);
std::cout << "Square (10 x 10) has area " << area (square) << std::endl;
Polygon triangle;
triangle.push_back (Coordinates (0, 0));
triangle.push_back (Coordinates (0, 6));
triangle.push_back (Coordinates (8, 0));
assert (area (triangle) == 24);
std::cout << "Right-angled triangle (width 8, height 6) has area " << area (triangle) << std::endl;
Polygon irregular;
irregular.push_back (Coordinates (0, 0));
irregular.push_back (Coordinates (0, 14));
irregular.push_back (Coordinates (8, 14));
irregular.push_back (Coordinates (8, 4));
irregular.push_back (Coordinates (12, 4));
irregular.push_back (Coordinates (12, 0));
assert (area (irregular) == 128);
std::cout << "6-sided irregular polygon has area " << area (irregular) << std::endl;
Polygon line;
line.push_back (Coordinates (0, 0));
line.push_back (Coordinates (0, 4));
line.push_back (Coordinates (0, 8));
assert (area (line) == 0);
std::cout << "3 points on a line of length 8 has area " << area (line) << std::endl;
}
How arrays used in vc plus plus?
Arrays are used to store two or more variables of the same type in contiguous memory. Since all elements are of the same type, they are also of the same size (in bytes), thus every element can be accessed as an offset from the start of the array. In an array of n elements, index 0 is the first element and index n-1 is the last element. By multiplying the index by the type size, the compiler can determine the start address of each element, thus permitting constant time, random access to any element within the array, as well as bi-directional traversal of the array.
Arrays provide the most compact method of storing multiple values of the same type. So long as you know the start address of the array (which is obtained by the array name alone) and the number of elements in the array (which must be stored separately), you can access any element in constant time.
C++ supports fixed-length arrays (std::array) and variable-length arrays (std::vector) as well as C-style arrays (both static and dynamic). In most cases you will use std::vector and std::array as they both provide bounds-checking, can be easily passed to functions by value, reference or pointer, and you enlist the compiler to ensure type safety. Both std::vector and std::array encapsulate the array, its type and its size, while std::vector uses a built-in memory manager to minimise reallocation of the array.
With C-style arrays, the onus is entirely upon the programmer to ensure bounds-checking and type safety are adhered to. In particular, passing a C-style array to a function via a pointer should be avoided as the function has no way to determine how many elements are actually in the array, let alone what type of elements were originally placed in the array.
What is number system what are various number system explain with a suitable example?
A number system is simply a way to record numbers. Humans have used a variety of numbering systems over the years, but the decimal system is by far the most prevalent today. This system uses the ten Arabic symbols, 0123456789, to represent the digits from zero to nine, and is known as base 10 for this reason. Digits are aligned on columns, with units on the right, 10s to their left, and 100's to their left, and so on. Each column is therefore 10 times the value of the column to its right. In other words, each column is an increasing power of 10, beginning with 10^0 on the right, then 10^1 and so on.
You are undoubtedly familiar with base 10, however the above is relevant when discussing other number systems as the same principals apply.
Computers use base 2 (binary), which is the lowest base of all. It uses the 2 Arabic digits, 0 and 1. Since it is base 2, the columns represent powers of 2. So the rightmost column represents 2^0, then 2^1, 2^2, 2^3, and so on the further left we go. So the number 4 in decimal would be represented by 100 in base 2. That is, 1 * (2^2), which is 4 (all other columns are zero, so they evaluate to zero).
Computer programmers use base 16 (hexadecimal). This is because binary numbers, despite their apparent simplicity, are incredibly difficult for humans to work with. One digit out of place could be disastrous. Converting them to decimal is clearly an option, but hexadecimal is a lot simpler to work with because base 2 and base 16 are interchangeable and align with each other more closely than decimal.
Four binary digits gives us 16 possible combinations. 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110 and 1111 (decimal zero to decimal 15, respectively). With only 16 combinations to consider, each of these can be represented by a single hexadecimal symbol. There are only 10 Arabic symbols for numbers, so we must use 6 additional symbols for the numbers 10 to 15. By convention we use the letters a through f. Thus each of the binary combinations above can be represented by 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e and f, respectively.
Binary digits (bits) are usually combined into groups of 8 bits, known as bytes. 8 is a multiple of 4, so we need 2 hexadecimal digits to represent a full byte. To do this we simply divide the byte into two half bytes (known as nybbles), then convert each nybble to its hexadecimal form. Thus the byte 01101101 is represented as nybbles 0110 and 1101, which is 5d in hexadecimal (often denoted as 0x5d). This equates to (5 * (16^1)) + (13 * (16^0)), which is 93 decimal. So 01101101 is binary for 93 decimal, or 0x5d hexadecimal.
Regardless of the length of a sequence of bits, breaking them into groups of 4 allows them to be translated directly into hexadecimal. So a 32-bit number requires 8 hexadecimal digits. Reading and writing 8 digits is clearly a lot simpler than deciphering 32 bits of 1s and 0s, and because binary and hexadecimal have a consistent alignment (4 bits equals 1 hex digit), they are much easier to deal with than decimal which has a more variable alignment with binary (4 bits could be 1 or 2 decimal digits).
Other bases that are in common use today include base 60, which is the basis for our clocks. 60 seconds is 1 minute and 60 minutes is 1 hour. Then we switch to base 12 for the hours (or base 24 if using a 24-hour clock). You may ask why we never "decimalised" our time-keeping (dividing the day into 10 or 20 longer hours, each with 100 minutes, each with 100 seconds, for instance). The main reason is that 60 is evenly divisible by 2, 3, 4, 5 and 6, whereas 100 is evenly divisible by just 2, 4 and 5, and a 12-hour period (which is also division of 60) is evenly divisible by 2, 3, 4 and 6 whereas 10 is evenly divisible by just 2 and 5.
Inches and feet are also base 12. So while we are quite familiar with base 10, we actually use other bases without realising it. Of course we don't symbolise numbers greater than 9 with letters like we do in hexadecimal, but the principal is the same.
#include<iostream>
#include<sstream>
using namespace std;
string digits {"0123456789+-.,"};
bool is_number (const string& str)
{
if (str.find_first_not_of(digits) != str.npos)
return false;
// If a plus sign is present, it must be the first character.
size_t f = str.rfind ('+');
if (f!=0 && f!=str.npos)
return false;
// If a minus sign is present, it must be the first character.
f = str.rfind ('-');
if (f!=0 && f!=str.npos)
return false;
// There can only be one decimal point at most.
size_t dot = str.find ('.');
if (dot != str.rfind ('.'))
return false;
// If a decimal point is present, it must not be the last character.
if (dot str.npos && comma != str.npos && (str.size()-comma)%4)
return false;
return true;
}
string get_first_number (const string& str)
{
for (auto b=str.begin(); b!=str.end(); ++b)
{
if (digits.find (*b) != digits.npos)
{
for (auto e=str.rbegin(); e.base()!=b; ++e)
{
if (digits.find (*e) != digits.npos)
{
auto t = e.base();
string n = str.substr (b-str.begin(), t-b);
if (is_number (n))
return n;
}
}
}
}
return "";
}
int main()
{
string text {"This string has the numbers 42, 1,000,000, 5,0, +1, -2, 3.14 and .5."};
string number;
cout << "Original string: "" << text << """ << endl;
cout << "\nNumbers:\n";
while ((number=get_first_number (text)).size())
{
cout << number << endl;
size_t pos = text.find (number);
text.replace (pos, number.size(), "\n");
}
cout << "\nStrings:\n";
stringstream ss;
ss << text << '\n';
while (!ss.eof())
{
getline (ss, text, '\n');
if (text.size())
cout << '"' << text << '"' << endl;
}
cout << endl;
}
What makes a vector so popular and useful in C plus plus?
A vector should always be considered the default container object unless you have good reason to use a more specialised container (such as a map, set or list).
A vector is essentially a variable-length array which automatically grows to accommodate new elements. If you require a fixed-length array, consider using std::array rather than std::vector or built-in array (C-style array).
As well as encapsulating the array and its current length, a vector also encapsulates a reserve to allow moderate expansion without reallocating the array upon every insertion. When the reserve is depleted, reallocation may occur however the optimum growth rate upon reallocation is around 160% which gives a reasonable balance between performance and memory consumption. You may set your own reserve if you can predict how many insertions you need to cater for, but in many cases there is very little to be gained by doing so.
Like all other standard-library containers, a vector is also a resource handle. That is, when a vector falls from scope, the elements within it are destroyed automatically. However, when the elements are pointers, the objects they refer to are not destroyed because pointers are not objects and therefore do not have destructors. The majority of vectors we use contain pointers, particularly when working with polymorphic objects (where we refer to a common base of the objects rather than the objects themselves). However, if a vector of pointers falls from scope before we destroy the objects it referred to, we create a resource leak.
To overcome this, we can easily populate vectors with smart pointers which are themselves resource handles with their own destructors. When the vector of smart pointers falls from scope, the smart pointers are destroyed automatically, which in turn automatically destroys the objects they referred to -- unless the smart pointer is a shared pointer in which case the object is only destroyed when the final reference falls from scope. Either way, we eliminate the risk of creating a resource leak at little to no cost (shared pointers incur some cost due to reference counting, but that cost is negligible compared to alternative solutions).
Being a resource handle, vectors implement the move semantic thus making it possible to pass and return vectors by value efficiently and at minimal cost. Built-in arrays, on the other hand, cannot be passed by value at all because arrays decay to pointers (hence we cannot implicitly copy a built-in array); we can only pass them by reference. However, because of the implicit decay to a pointer, passing a built-in array by reference is actually slightly less efficient than passing a vector by reference because the pointer alone does not tell us how many elements it refers to, so we also need to pass the array size. A vector carries all information with it, so passing the reference alone suffices.
All operators must return a value, and it is this return value (the evaluation of the operation) that differentiates the pre-increment and post-increment operators. If the return value is of no concern, then the pre-increment operator is the preferred version, particularly when working with objects. This is because the post-increment operator's implementation will generally make a copy of the original object which it will return after incrementing the original object. If the return value is of no concern, then making a copy adds an expensive overhead (this doesn't apply to primitive data types since CPU optimisation can pre-empt the return value without requiring a copy to be made).
Applications for post-increment and pre-increment are many and varied, but ultimately the goal is to increment the value. Whether you use post-increment or pre-increment is largely down to whether you need to use the return value or not, and whether you need to use the original value or the incremented value.
Although the same thing can be achieved with longhand code, it is more efficient to use the appropriate post-increment or pre-increment operators.
For instance:
int x=1;
int y=x;
++x;
Can be implemented more efficiently with:
int x=1;
int y= x++;
Whereas:
int x=1;
++x;
int y=x;
Can be implemented more efficiently with:
int x=1;
int y= ++x;
Use caution when pre-incrementing the same value in a compound statement. For example:
int x=0;
int y= ++x * ++x;
The expected result is 2, but the actual result is 4. This is because both expressions (++x) return the same value: a reference to x. And since x is incremented twice, the expression evaluates to 2*2, not 1*2.
To get the expected result of 2, each operation must be evaluated separately:
int x=0;
int y= ++x;
y*= ++x;
Code for triangular matrix using c plus plus?
#include<iostream>
#include<vector>
class triangular_matrix_t
{
private:
std::vector < std::vector<unsigned> > m_matrix;
unsigned m_gradiant;
public:
triangular_matrix_t (unsigned rows, unsigned initial_length = 1,
unsigned gradiant = 1): m_matrix (rows), m_gradiant (gradiant)
{
unsigned row_length = initial_length;
for (unsigned row=0; row<rows; ++row)
{
m_matrix[row].resize (row_length);
row_length += m_gradiant;
}
}
void set (unsigned row, unsigned column, unsigned value)
{
if (row<m_matrix.size())
{
if (column<m_matrix[row].size())
{
m_matrix[row].at(column) = value;
}
}
}
unsigned at(unsigned row, unsigned column)
{
if (row<m_matrix.size() && column<m_matrix[row].size())
return(m_matrix[row].at(column));
return 0;
}
unsigned get_height() const {
return(m_matrix.size()); }
unsigned get_length(const unsigned row) const {
return row<m_matrix.size() ? m_matrix[row].size() : 0; }
unsigned get_gradiant() const {
return m_gradiant; }
};
std::ostream& operator<< (std::ostream& os, triangular_matrix_t& matrix)
{
for (unsigned row=0; row<matrix.get_height(); ++row)
{
for (unsigned col=0; col<matrix.get_length(row); ++col)
{
os << matrix.at(row, col) <<'\t';
}
os << std::endl;
}
return os;
}
int main()
{
triangular_matrix_t matrix (10);
for (unsigned row=0; row<matrix.get_height(); ++row)
{
for (unsigned col=0; col<matrix.get_length(row); ++col)
{
matrix.set (row, col, (row+1)*(col+1));
}
}
std::cout << "Triangular matrix with 10 rows:\n" << std::endl;
std::cout << matrix << std::endl;
}
Output:
Triangular matrix with 10 rows:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100
How to write a program in c plus plus to print table of even number?
void print_evens (size_t n) {for (size_t x=0; x<=n; x+=2) {
std::cout << x << std::endl;
}
}
Overloading has nothing to do with inheritance. Overloading is simply a means by which you can provide two or more different ways to call the same function, according to the number and type of arguments you pass to the function.
Overriding is where a derived method provides a new implementation for a base class method. The override may augment the base class method simply by calling the base class method at any time, thus the new implementation need only cater for any differences between the two implementations.
Hiding occurs when you override a base class method that is also overloaded. All the base class overloads are effectively hidden by the overridden method, making them unavailable to the derived class. You must override each overload in order to make it visible to the derived class.
Ideally, you should only override methods that are declared virtual in the base class. In this way you gain the benefits of polymorphic behaviour: when you implicitly call a base class method, the override will be executed instead, thus ensuring all derived objects exhibit correct behaviour, even without prior knowledge as to what those derivatives may be.
Shadowing is similar to hiding insofar as the override "masks" the base class method. However, shadowing is more concerned with nested code blocks that declare the same variable name within the same namespace, and therefore has nothing whatsoever to do with inheritance. For instance, in the following example, the integer i in the outer code block is shadowed by the integer i in the inner code block. What this means is that the value of i in the outer block is not accessible to the inner block, because the i in the inner block masks it. Although this behaviour can sometimes be desirable, it is best avoided as it can lead to ambiguity about which instance of i you are actually referring to, and makes your code that much harder to follow.
for(int i=0; i<3; ++i )
{
std::cout<<i<<std::endl;
for(int i=0; i<3; ++i)
{
std::cout<<i<<" ";
}
std::cout<<std::endl;
}
Output:
0
0 1 2
1
0 1 2
2
0 1 2
What is the difference between active and passive objects in c plus plus?
Passive objects encapsulate state and operations, whereas active objects also encapsulate a process. Standard C++ does not support active objects.
What is function Explain the user define function with example?
Function is a logically grouped piece of code allowing perform certain types of operations. Function can return value (int, double etc) or be void type - meaning they do not return value.
Functions allow to make code cleaner by moving out chunks of code of main body. For instance you want to write a function that finds area of rectangular.
#include <iostream>
using std cin;
using std cout;
using std endl;
using std get;
int main()
{
double sideA = 0.0;
cout << "Enter side a of rectagular: ";
cin >> sideA;
double sideB = 0.0;
cout << endl << "Enter side b of rectangular: ";
cin >> sideB;
//This part passes sides a and b to user defined function "Square"
cout << endl << "Area of rectangular is: " << Square(a, b);
cin.get();
return 0;
}
//definition of user defined function Square
double Square(double a, double b)
{
return (a * b);
}