What is syntex error in c plus plus?
A string is a sequence of character data types typically stored in a vector or an array. The two main string classes are std::string and std::wstring, both of which can be found in the <string> header file. std::string is a specialisation of std::vector<char> while std::wstring specialises std::vector<wchar_t>. The latter is often known as wide-string, ideally suited to UTF-16 encoding. The former can be used for both ASCII and UTF-8 encoding. These are generally all you need.
You can construct objects of the string classes as follows:
std::string str ("Hello world!"); // C++ string
std::wstring wstr (L"Hello world!"); // C++ wide-string
You can also make use of C-style strings, however it's best to limit their use to fixed-length strings. These can be declared as follows:
char cstr[] = "Hello world!";
wchar_t cwstr[] = L"Hello world!";
You can use variable length C-strings if you wish but you're simply creating unnecessary work for yourself. The only real advantage is that you save some memory (4-bytes per string on a 32-bit system) but restrict yourself to the C standard library functions, most of which are inefficient compared to the equivalent C++ string member methods (primarily because the size of a C++ string does not need to be continually recalculated -- it is a given). C++ strings are also easily converted to and from C-style strings and they manage their own resources for you, which ultimately makes them much easier to use.
Although not physically part of the Standard Template Library, C++ strings adhere to STL semantics, including bidirectional, random-access iteration through the character sequence as well as subscript notation to access individual characters. STL algorithms and functions can also be applied, although the member functions are sufficient for most of the operations you will need to perform upon strings, such as appending strings and searching within strings.
Note that insertion of one string within another is not supported. This is because vectors are specifically designed to add new elements to the end of the sequence rather than the middle or beginning of the sequence. To insert one string inside another, it is more efficient to create a new string, reserving the number of characters required for both the original string plus the inserted sub-string, and simply appending the sub-strings accordingly. The new string can then be assigned to the original string if required.
By reserving characters, the new string doesn't have to be resized with each append operation. Resizing only occurs when an append operation exceeds the current allocation and may result in a reallocation if the current memory block has no room to expand. Reallocations are expensive as the original string must be copied to the new allocation, which means you need more than double the memory of the original allocation (at least for the duration of the copy operation), not to mention the performance impact of physically copying the string. The fewer reallocations you make the better, so plan ahead. Calculate and reserve what you need in advance.
C++11 also introduces move semantics which helps eliminate a lot of the copying operations that would otherwise occur when passing string values to or from functions (thus creating temporary strings). For instance, when you assign a function that returns a string to another string, two complete copies of the string are made. The first is made by the function itself, copying its local string to the function's return value (thus creating a temporary). The second is made when that return value is subsequently assigned to your string (if you don't assign, the temporary simply falls from scope, but still results in an unnecessary copy being made). With move semantics, no copies are made, the temporary simply takes ownership of the function's string and then passes that ownership onto your string.
This is made possible by the fact a string is nothing more than a pointer to a memory allocation plus the size of that allocation (in characters). By passing these two values alone, the new string immediately takes ownership of the allocation. The old string simply nullifies its pointer so when it falls from scope it doesn't destroy the allocation. As an implementation detail, all the actual work is done behind the scenes so the user is largely unaware of what's going on, the only visible sign being the much-improved performance. Move semantics apply to the entire STL in C++11 but can also be applied to your own classes. If you classes "own" resources, remember to provide move semantics so they can pass that ownership on automatically. Move semantics are achieved through a move constructor as well as a move assignment operator. It won't entirely eliminate the need to copy objects, but it will completely eliminate the need to make unnecessary copies.
Can c plus plus run on windows?
Windows 7 supports programs written in any language, including C and C++. However, the question is whether these programs support Windows 7 or not. If they were written for another platform entirely, such as the Apple Mac, then obviously they won't be supported.
Note that neither the C nor C++ languages, by themselves, support any particular operating systems, but they are generic enough to be able to create console applications that can run on most platforms without major modification. But in order to target a specific platform you need the appropriate headers and libraries for that platform. These are generally provided by your integrated development environment (IDE) of which there are many to choose from for each platform. In order to cater for multiple platforms code must be written specifically for each platform (using precompiler directives to filter out unwanted code) and must be compiled separately upon each supported platform.
C plus plus program of a palindrome?
There are several ways to determine if a string is a palindrome or not. Typically, you must first ignore all spacing, capitalisation and punctutation within the string, which can be done by copying the string, character by character, ignoring all non-alphanumeric characters. You then point to the first and last characters in the modified string and, so long as both characters under the pointers are the same, work the pointers towards the middle of the string until the pointers either meet in the middle or they pass each other. That is, if the string has an odd count of characters, the pointers will meet at the middle character, otherwise they will pass each other. At that point you can say with certainty the string is a palindrome. If the characters under the pointers differ at any time, then the string is not a palindrome. This is fairly straightforward to program.
A more interesting problem is when you have to locate the longest palindrome within a string which is not itself a palindrome. For instance, the string "Madam, I'm Adam is a palindrome" is not a palindrome, but it does contain one: "Madam I'm Adam". In this case we cannot point to the first and last characters and work towards the middle. Instead, we have to test every possible substring of the string. We do this by starting at the first character and treat it as if it were actually the middle character of a palindrome, and then move our pointers to the left and right of this character while the characters match. When they no longer match, or one of the pointers has reached either end of the string, we store the longest palindrome found up to that point and then move onto the next character and treat it as the middle character. If we continue in this manner, treating every character as if it were the middle character of a palindrome, we will eventually locate the longest palindrome.
The problem with this approach is when the longest palindrome has an even number of characters instead of an odd number. To get around this we simply place a single space between each character, and treat each of those as being the middle character as well. When a palindrome is found, we simply remove the spaces. In this way we can use exactly the same algorithm to cater for both odd and even character palindromes.
The only remaining problem is when we wish to print the palindrome itself. Since this will be a substring of the original string, we cannot use the modified string we used to locate the palindrome. One way to get around that is to store the original positions of each letter in an array of indices, and use that array to determine where the substring lies with in the original string.
The following program demonstrates this technique in full. The key function is the ispalindrome() function, which accepts a lower-case copy of the string (including the original spacing an punctuation), and a vector that contains the indices of each letter within the string (ignoring puctuation and spacing), separated by -1 values (representing the implied spaces between each letter). The pos value tells the function which index of the vector is to be treated as the middle character of the potential palindrome, while x and y are output parameters that determine the start and end of the palindrome within the vector. The function returns true if a palindrome was found, and the x and y values can be used to extract the palindrome from the original string, using the indices stored in the vector. Note that when the search for a palindrome fails, we step back the x and y indices by one, and if the vector index is -1, then we step back another index. We then test the x and y values to see if they indicate a palindrome was found or not.
The strip() function is another key function. This generates the vector from the lower case copy of the original string. Although we could eliminate the -1 values at the start and end of the vector, it's simpler to just leave them in.
You will note that the program can cater for strings that are themselves palindromes, as well as strings that contain palindromes.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string input_string(string prompt)
{
cout<<prompt<<":\t";
string input;
getline(cin, input, '\n');
return(input);
}
void convert_tolower(string& s)
{
for(string::iterator i=s.begin(); i!=s.end(); ++i)
*i=tolower(*i);
}
vector<int> strip(const string& s)
{
vector<int> v;
v.push_back(-1);
for(int i=0; i<s.size(); ++i)
{
if((s[i]>='a' && s[i]<='z') (s[i]>='0' && s[i]<='9'))
{
v.push_back(i);
v.push_back(-1);
}
}
return(v);
}
bool ispalindrome(const string s, const vector<int> v, int pos, int& x, int& y)
{
for(x=pos,y=pos; x>=0 && y<v.size(); --x, ++y)
if( v[x]!=-1 && ( s[v[x]]!=s[v[y]] ))
break;
++x, --y;
if( v[x]==-1 )
++x, --y;
return(x>=0 && x<y && y-x>1);
}
int main()
{
string input;
while(1)
{
input=input_string("Enter a string");
if(input.size()==0)
break;
string copy(input);
convert_tolower(copy);
vector<int> v=strip(copy);
string pal;
int pos=0;
for(int i=0; i<v.size(); ++i)
{
int start=0, end=0;
if( ispalindrome( copy, v, i, start, end))
{
string tmp( input.substr(v[start],v[end]-v[start]+1));
if( tmp.size() > pal.size() )
{
pal = tmp;
pos = v[start];
}
}
}
if( pal.size() )
{
cout<<"Palindrome:\t";
for(int i=0; i<pos; ++i)
cout<<" ";
cout<<pal<<"\n"<<endl;
}
else
cout<<"The string contains no palindromes!\n"<<endl;
}
return(0);
}
Example output:
Enter a string: Madam, I'm Adam
Palindrome: Madam, I'm Adam
Enter a string: Madam, I'm Adam is a palindrome
Palindrome: Madam, I'm Adam
Enter a string: In girum imus nocte et consumimur igni
Palindrome: In girum imus nocte et consumimur igni
Enter a string: 0123456765432
Palindrome: 23456765432
Enter a string:
Press any key to continue . . .
How can a node be inserted in the middle of a linked list?
when you have two nodes and when you want to insert the third node between the 1 & 2 then, store the address of the third in the next pointer of 1st and address of 2nd in the next pointer of 3rd.
by kochu
What is the importance of functions in c plus plus?
Without functions, a non-trivial program would contain repeated code segments and would be extremely difficult to maintain. Even if you don't write any functions of your own, you still have to call the built-in functions to actually do anything worthwhile.
User-defined functions allow you to structure your source code more efficiently. If you find yourself writing the same code segment over and over, then it makes sense to turn it into a function. Apart from anything else, it reduces the chance of making a mistake or a typo. And with only one copy of the code it becomes that much easier to adjust the function to improve its efficiency or add additional functionality. Moreover, you can break large and complex problems down into smaller functions, each of which can be broken down further if required. This is known as re-factoring. The end result is your code becomes much easier to read and is therefore much easier to maintain.
Every function you write should do a small amount of work, and should do it extremely well and as efficiently as possible. A one-line comment is usually more than sufficient to describe the purpose of a function. But if your function is large and complex, and heavily commented, re-factoring should be considered -- especially if you find it difficult to follow yourself.
While there is a performance penalty in making a function call, your compiler should be intelligent enough to work out which functions can be inline expanded (just as if you'd duplicated the code yourself). In general, only trivial and heavily repeated functions will be inline expanded, and only if the compiler believes there to be an advantage in doing so. While you can tell it which functions to inline expand, the compiler is usually free to ignore the request if it sees no advantage in doing so. Additional optimisers will check the resulting machine code more closely and make finer adjustments as they see fit. The end result should be reasonably efficient code, the only real compromise being overall code size vs. overall code speed (large code is not necessarily fast code).
What is the function of dos.h?
You can find a copy of that file in here:
http://ftp.ibiblio.org/pub/micro/PC-stuff/freedos/files/devel/c/dos.h
in case the server is down check the extracted file:
#ifndef __DOS_H
#define __DOS_H
#include <_defs.h>
#include <stddef.h>
#ifdef __WATCOMC__
#pragma pack( __push, 1 )
#endif
struct _R16BIT {
unsigned short ax, bx, cx, dx, si, di, es, cs, ss, ds, flags;
unsigned char cflag;
};
struct _R8BIT {
unsigned char al, ah, bl, bh, cl, ch, dl, dh;
};
union _INTR {
struct _R16BIT x;
struct _R8BIT h;
};
#define INTR _INTR
struct country {
int co_date; /* date format */
char co_curr[ 5 ]; /* currency symbol */
char co_thsep[ 2 ]; /* thousands separator */
char co_desep[ 2 ]; /* decimal separator */
char co_dtsep[ 2 ]; /* date separator */
char co_tmsep[ 2 ]; /* time separator */
char co_currstyle; /* currency style */
char co_digits; /* significant digits in currency */
char co_time; /* time format */
long co_case; /* case map */
char co_dasep[ 2 ]; /* data separator */
char co_fill[ 10 ]; /* filler */
};
#define COUNTRY country
struct DOSERROR {
int de_exterror; /* extended error */
char de_class; /* error class */
char de_action; /* action */
char de_locus; /* error locus */
};
struct date {
unsigned int da_year; /* current year */
unsigned char da_day; /* day of the month */
unsigned char da_mon; /* month (1 = Jan) */
};
struct dosdate_t {
unsigned char day; /* 1--31 */
unsigned char month; /* 1--12 */
unsigned int year; /* 1980--2099 */
unsigned char dayofweek; /* 0--6; 0 = Sunday */
};
struct devhdr {
long dh_next;
short dh_attr;
unsigned short dh_strat;
unsigned short dh_inter;
char dh_name[ 8 ];
};
struct dfree {
unsigned df_avail; /* Available clusters */
unsigned df_total; /* Total clusters */
unsigned df_bsec; /* Bytes per sector */
unsigned df_sclus; /* Sectors per cluster */
};
struct diskfree_t {
unsigned total_clusters;
unsigned avail_clusters;
unsigned sectors_per_cluster;
unsigned bytes_per_sector;
};
typedef struct {
char drive;
char pattern [ 13 ];
char reserved [ 7 ];
char attrib;
short time;
short date;
long size;
char nameZ [ 13 ];
} dosSearchInfo;
struct fatinfo {
char fi_sclus; /* sectors per cluster */
char fi_fatid; /* the FAT id byte */
int fi_nclus; /* number of clusters */
int fi_bysec; /* bytes per sector */
};
struct ffblk {
#ifdef __CLIB_LFN__
unsigned short cr_time; /* time of file creation */
unsigned short cr_date; /* date of file creation */
unsigned short ac_time; /* time of last file access */
unsigned short ac_date; /* date of last file access */
char ff_reserved[ 13 ]; /* reserved for use by DOS */
#else
char ff_reserved[ 21 ]; /* reserved for use by DOS */
#endif
char ff_attrib; /* attribute byte for file */
unsigned short ff_ftime; /* time of last write to file */
unsigned short ff_fdate; /* date of last write to file */
unsigned long ff_fsize; /* length of file in bytes */
#ifdef __CLIB_LFN__
char ff_name[ 256 ]; /* null-terminated filename */
unsigned short lfnhandle;/* DOS LFN support handle */
#else
char ff_name[ 13 ]; /* null-terminated filename */
#endif
};
struct find_t {
#ifdef __CLIB_LFN__
unsigned short cr_time; /* time of file creation */
unsigned short cr_date; /* date of file creation */
unsigned short ac_time; /* time of last file access */
unsigned short ac_date; /* date of last file access */
char reserved[ 13 ]; /* reserved for use by DOS */
#else
char reserved[ 21 ]; /* reserved for use by DOS */
#endif
char attrib; /* attribute byte for file */
unsigned short wr_time; /* time of last write to file */
unsigned short wr_date; /* date of last write to file */
unsigned long size; /* length of file in bytes */
#ifdef __CLIB_LFN__
char name[ 256 ]; /* null-terminated filename */
unsigned short lfnhandle;/* DOS LFN support handle */
#else
char name[ 13 ]; /* null-terminated filename */
#endif
};
#define _find_t find_t
struct fcb {
char fcb_drive;
char fcb_name[ 8 ],
fcb_ext[ 3 ];
short fcb_curblk,
fcb_recsize;
long fcb_filsize;
short fcb_date;
char fcb_resv[ 10 ],
fcb_currec;
long fcb_random;
};
struct xfcb {
char xfcb_flag;
char xfcb_resv[ 5 ];
char xfcb_attr;
struct fcb xfcb_fcb;
};
struct dostime_t {
unsigned char hour; /* Hours */
unsigned char minute; /* Minutes */
unsigned char second; /* Seconds */
unsigned char hsecond; /* Hundredths of seconds */
};
struct time {
unsigned char ti_min; /* minutes */
unsigned char ti_hour; /* hours */
unsigned char ti_hund; /* hundredths of seconds */
unsigned char ti_sec; /* seconds */
};
#ifdef __WATCOMC__
#pragma pack( __pop )
#endif
extern int __getversion( void );
extern char ** environ;
#define _version (*__getversion)()
extern unsigned char _osmajor;
extern unsigned char _osminor;
extern int absread( int drive, int sects, long lsect, void *buffer );
extern int abswrite( int drive, int sects, long lsect, void *buffer );
extern int allocmem( unsigned size, unsigned *seg );
extern int bdos( int ah, unsigned dx, unsigned al );
extern int bdosptr( int ah, void *argument, unsigned al );
extern int _callint( union INTR *regs );
extern struct COUNTRY *
country( int xcode, struct COUNTRY *ct );
extern void ctrlbrk( int ( *handler )( void ) );
extern void delay( unsigned mill );
extern void _disable( void );
extern unsigned _dos_allocmem( unsigned size, unsigned *seg );
extern unsigned _dos_close( int handle );
extern unsigned _dos_creat( const char *path, int attr, unsigned *handle );
extern unsigned _dos_creatnew( const char *path, int attr, unsigned *handle );
extern int __cdecl dosexterror( struct DOSERROR *errblk );
extern unsigned _dos_findfirst( char *filename, int attrib, void *strptr );
extern unsigned _dos_findnext( void *strptr );
extern unsigned _dos_findclose( void *strptr );
extern unsigned _dos_freemem( unsigned seg );
extern void __cdecl _dos_getdate( struct dosdate_t *ptr );
extern unsigned __cdecl
_dos_getdiskfree( unsigned char dr, struct diskfree_t *d );
extern unsigned _dos_getdrive( unsigned *disk );
extern unsigned _dos_getfileattr( const char *filename, unsigned *attrs );
extern unsigned __cdecl
_dos_getftime( int handle,
unsigned *date,
unsigned *time );
extern void __cdecl _dos_gettime( struct dostime_t *timeptr );
extern void ( interrupt far *
_dos_getvect( unsigned intno ) )( );
extern void _dos_keep( unsigned char retcode, unsigned size );
extern unsigned _dos_open( const char *path, unsigned flags, unsigned *handle );
extern unsigned _dos_read( int handle,
void far *buf,
unsigned len,
unsigned *nread );
extern unsigned _dos_setblock( unsigned newsize,
unsigned seg,
unsigned *max );
extern void _dos_setdate( struct dosdate_t *ptr );
extern void _dos_setdrive( unsigned disk, unsigned *total );
extern unsigned _dos_setfileattr( const char *filename, unsigned attrs );
extern unsigned _dos_setftime( int handle, unsigned date, unsigned time );
extern unsigned _dos_settime( struct dostime_t *timeptr );
extern void _dos_setvect( unsigned intno,
void ( interrupt far *vect )() );
extern time_t dostounix( struct date *date, struct time *time );
extern unsigned _dos_write( int handle,
void far *buf,
unsigned len,
unsigned *bytes );
extern void _enable( void );
extern int freemem( unsigned seg );
extern int getcbrk( void );
extern void __cdecl getdate( struct date *datep );
extern void __cdecl getdfree( unsigned char drive, struct dfree *dtable );
extern char * getdta( void );
extern void getfat( unsigned char drive, struct fatinfo *dtable );
extern void getfatd( struct fatinfo *dtable );
extern unsigned getpsp( void );
extern void __cdecl gettime( struct time *timeptr );
extern void ( interrupt far *
getvect( int intno ) )( );
extern int getverify( void );
extern int inp( unsigned id );
extern unsigned inpw( unsigned id );
extern unsigned inport( unsigned id );
extern unsigned char inportb( unsigned id );
extern void keep( unsigned char retcode, unsigned size );
extern void nosound( void );
extern int outp( unsigned id, int value );
extern unsigned outpw( unsigned id, unsigned value );
extern void outport( unsigned id, unsigned value );
extern void outportb( unsigned id, unsigned char value );
extern char * parsfnm( const char *cmdline, struct fcb *ptr, int al );
extern int peek( unsigned seg, unsigned offs );
extern char peekb( unsigned seg, unsigned offs );
extern void poke( unsigned seg, unsigned offs, int value );
extern void pokeb( unsigned seg, unsigned offs, char value );
extern int randbrd( struct fcb *buf, int rnum );
extern int randbwr( struct fcb *buf, int rnum );
extern int setblock( unsigned newsize, unsigned seg );
extern int setcbrk( int value );
extern void setdate( struct date *datep );
extern void setdta( char far *dta );
extern void setpsp( unsigned psp );
extern void settime( struct time *timeptr );
extern void setvect( int intno, void ( interrupt far *vect )() );
extern void setverify( int flag );
extern void sleep( unsigned x );
extern void sound( unsigned frequency );
extern void unixtodos( time_t longtime,
struct date *date,
struct time *time );
extern int unlink( const char *filename );
#define disable _disable
#define enable _enable
#define _A_NORMAL 0x00
#define _A_RDONLY 0x01
#define _A_HIDDEN 0x02
#define _A_SYSTEM 0x04
#define _A_VOLID 0x08
#define _A_SUBDIR 0x10
#define _A_ARCH 0x20
#define FA_NORMAL _A_NORMAL
#define FA_RDONLY _A_RDONLY
#define FA_HIDDEN _A_HIDDEN
#define FA_SYSTEM _A_SYSTEM
#define FA_LABEL _A_VOLID
#define FA_DIREC _A_SUBDIR
#define FA_ARCH _A_ARCH
#define NFDS 20
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#define MK_FP( seg, ofs ) ( ( void * )\
( ( ( unsigned long )( seg ) << 16 ) |\
( unsigned )( ofs ) ) )
#define FP_SEG(fp) ( ( unsigned )( ( unsigned long )( fp ) >> 16 ) )
#define FP_OFF(fp) ( ( unsigned )( fp ) )
#define __peek( a,b ) ( *( ( int far * ) MK_FP ( ( a ), ( b ) ) ) )
#define __peekb( a,b ) ( *( ( char far * ) MK_FP ( ( a ), ( b ) ) ) )
#define __poke( a,b,c ) ( *( ( int far * ) MK_FP ( (a),(b)) ) = ( int )(c))
#define __pokeb( a,b,c ) ( *( ( char far * ) MK_FP ( (a),(b)) ) = ( char )(c))
#define peek( a,b ) ( *( ( int far * ) MK_FP ( ( a ), ( b ) ) ) )
#define peekb( a,b ) ( *( ( char far * ) MK_FP ( ( a ), ( b ) ) ) )
#define poke( a,b,c ) ( *( ( int far * ) MK_FP ( (a),(b)) ) = ( int )(c))
#define pokeb( a,b,c ) ( *( ( char far * ) MK_FP ( (a),(b)) ) = ( char )(c))
#ifndef __NO_INLINE_FUNCTIONS
#pragma aux _enable = "sti";
#pragma aux _disable = "cli";
#pragma aux inp = "in al, dx" parm [dx] value [al] modify [ax dx];
#pragma aux inpw = "in ax, dx" parm [dx] value [ax] modify [ax dx];
#pragma aux inport = "in ax, dx" parm [dx] value [ax] modify [ax dx];
#pragma aux inportb = "in al, dx" parm [dx] value [al] modify [ax dx];
#pragma aux outp = "out dx, al" parm [dx] [al] value [al] modify [ax dx];
#pragma aux outpw = "out dx, ax" parm [dx] [ax] value [ax] modify [ax dx];
#pragma aux outport = "out dx, ax" parm [dx] [ax] modify [ax dx];
#pragma aux outportb = "out dx, al" parm [dx] [al] modify [ax dx];
#endif
#endif
When do you use protected visibility specifier to a class member in C?
a class member declared as private can only be accessed by member functions and friends of that class
a class member declared as protected can only be accessed by member functions and friends of that class,and by member functions and friends of derived classes
What are the implecations of making a function pure virtual function?
Only class instance methods can be rendered as pure-virtual functions (or pure-virtual methods, to be precise). Non-member functions and static member methods cannot be declared pure-virtual.
The implication of declaring a pure-virtual function is that the class to which it is a member becomes an abstract data type (or abstract base class). This means you cannot instantiate an object of that class, you can only derive classes from it. Moreover, the derived classes must also implement the pure-virtual functions or they, too, become abstract data types. Only concrete classes that contain a complete implementation can be instantiated, although they can inherit implementations from their base classes (but not from the class that initially declared the method).
Pure-virtual functions ensure that you do not instantiate base class objects that are not intended to be instantiated (they are conceptual rather than actual objects) and that derived objects provide a specific implementation. Typically, all methods of an abstract base class will be declared pure-virtual to ensure correct behaviour in derived classes through a common interface. Abstract base classes will also have few member variables, preferably none at all.
For example, a shape is a conceptual object whereas a rectangle, triangle or circle are actual objects. As such they can all be derived from shape. The shape base class need only declare the interface that is common to all shapes, such as Draw(), Rotate(), Mirror() and so on. But since a shape doesn't have enough information to implement these methods, they must be declared pure-virtual. This ensures that shape cannot be instantiated (since it would be meaningless) and that every object derived from shape not only has a common interface, but that each type of shape provides its own specific implementation of those methods. This is not unlike overriding standard virtual functions, however the difference is that you must override the pure-virtual methods; it is not optional unless the derived class is intended to become abstract itself.
Why a friend function cannot be used to overload the assignment operator?
Assignment(=) operator is a special operator that will be provided by the constructor to the class when programmer has not provided(overloaded) as member of the class.(like copy constructor).
When programmer is overloading = operator using friend function, two = operations will exists:
1) compiler is providing = operator
2) programmer is providing(overloading) = operator by friend function.
Then simply ambiguity will be created and compiler will gives error. Its compilation error.
How can template increase the code reusebility in c plus plus?
Templates encourage generic programming. When classes or functions only differ by type, there is no need to write the same implementations over and over -- the compiler generates the functions or classes from the template. You can also cater for specialisation, so if you need a more specific implementation for pointers to types rather than actual types, you can provide the code to cater for this, without the need to duplicate already existing code that caters for all types.
What is object oriented programming language in C plus plus?
C program to print number in reverse order?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int r=0,d,m,n;
printf("Enter a value=");
scanf("%d",&n);
m=n;
do
{
d=m%10;
m=m/10;
r=(r*10)+d;
}
while(m!=0);
printf("%d is the reverse",r);
getch();
}
How cold boot different a warm boot?
A cold boot always begins with the power off whereas a warm boot does not interrupt the power supply. Although there may not appear to be any difference on the surface (a POST is performed regardless), a cold boot is more reliable as it ensures all hardware is properly reset.
When diagnosing hardware issues, it's always best to cold boot the system to ensure consistency. It's also best to let the system rest for at least 30 seconds to allow any residual current to drain before powering up again. Ideally, external peripherals (USB drives, printers, domestic routers, etc) should be turned off as well. Hardware issues are problematic enough without increasing the number of variables you have to contend with.
#include
#include
void main()
{ char str[50];
int i,count,countc;
printf("Enter a string : ");
gets(str);
count=0;
i=0;
while(str[i]!='\0′)
{ if(str[i]==' ')
count++;
i++;
}
printf("The total number of words are %d ",count+1);
}
Read more: http://programmingkid.com/count-number-of-words-in-a-string/#ixzz1aGIR1odb
Write a c program to compare two strings without using builtin function?
A string is a character array, so you can compare them one character at a time:
String x = "test"
String y = "test"
for(int i = 0; i < x.length && i < y.length; i++)
{
if(x[i] != y[i])
return false;
}
return true;
Write a C plus plus program for enumeration and function overloading?
All operators can be overloaded with the exception of the sizeof, typeid, member-of (.), pointer to member (.*), ternary conditional (?:) and scope resolution (::) operators.
Operators may be unary (those that accept one operand) or binary (those that accept two operands). The ternary conditional operator is the only operator that accepts three operands but it cannot be overloaded.
Before overloading an operator, you must first consider the types of its operand(s) and also the type of its return value. All operators must return something, whether it is the logical NOT of an object (a unary operation) or the sum of two objects (a binary operation). However it's easy to get carried away with overloads in order to cater for every possible combination of types, and this can quickly lead to code duplication, inconsistencies and code that is much harder to maintain.
Ideally, all operators should be implemented as free functions (global functions). In so doing you gain the advantage of implicit conversion between types, thus reducing the number of overloads required for any given operation. The only operator overloads that must be implemented as member functions are the copy and move assignment operators, so let's begin with those.
Let's consider a class that encapsulates a year. We'll assume negative years denote BC and positive years denote AD, thus we'll use a signed integral as our representation. However, there was no year zero (we went from 1BC to 1AD), thus our class has an invariant -- it must not be zero.
class year
{
private:
int64_t m_data; // 64-bit signed integral
public:
year (int64_t y): m_data {y} { if (!y) throw std::range_error ("Error: no year zero!"); }
year (const year& y): m_data {y.m_data} {}
year (year&& y): m_data {std::move (y.m_data)} {}
year& operator= (const year& y) {m_data = y.m_data; }
year& operator= (year&& y) { m_data = std::move (y.m_data); }
~year () {}
};
Our class has one conversion constructor which allows us to implicitly convert from any 64-bit integer to a year. However, since the language has built-in conversions for all integrals we can implicitly construct a year from any integral, including a char, an int, a long, a short and so on. The only integral type we cannot implicitly convert is an unsigned 64-bit integral since this could exceed the bounds of our signed integral by up to an order of two. However, the compiler should warn us about this "narrowing" and helps us keep the class as simple as possible.
Note that the conversion constructor is the only constructor that maintains the invariant (non-zero years). Since the copy and move constructors can only work with pre-existing instances of our year class, those instances would not exist unless they had originally been constructed through conversion.
The copy and move assignment operators also cater for pre-existing instances of our year class, but we can also assign from any signed integral because we provided a conversion constructor to cater for this. This makes it possible to perform the following:
year y {2014};
y = -1;
The first statement initialises a year with the literal integral 2014. That is, the value 2014 is implicitly converted to an int64_t (which is what the conversion constructor expects), and the constructor instantiates a year object with that value. The second statement replaces that value with the literal integral -1 even though we did not provide an assignment operator overload to cater for this. Behind the scenes, the compiler constructs a temporary year object from the literal (just as it did with 2014), and then uses that temporary object to perform the actual assignment. The temporary object falls from scope at the end of the statement.
The stream insertion and extraction operators often cause problems for new programmers in the mistaken belief that all operators related to a class should be members of that class just as the copy and move assignment operators must be. However, this is not the case; all other operator overloads should ideally be non-member functions whenever possible, especially when the return value is of a different type. In this case the return value is a reference to the stream being operated upon. We cannot provide these overloads as members of the stream nor as members of the type, therefore we have no option but to define them as free functions:
std::ostream& operator<< (std::ostream& os, const year& y)
{
return os << y.m_data;
}
The problem with this is that year::m_data is private. We could provide a public accessor (in many cases this would be the preferred option), but we must also never expose an interface without good reason. If this were the only function that actually required that accessor then it would not make sense to provide one. A public accessor is intended to be used by anyone and everyone. In this case we could simply return the member by value (and thus maintain encapsulation of the invariant), but in a more complex object we may not wish to expose the entire representation in this way because returning by value can be expensive in terms of both performance and memory. Returning by constant reference is another option but, again, this could expose far more than we wish to expose, which ultimately undermines the encapsulation. The best solution is simply to declare those functions that require private access as friends of the class:
class year
{
// ...
friend std::ostream& operator<< (std::ostream&, const year&);
};
Note that a friend is not a member of the class that declares it a friend, nor does it undermine encapsulation (if anything, it enforces it). The best way to think of it is to examine the three logically distinct things that every ordinary member function declaration specifies:
1. The function has private access to the class representation.
2. The function is in the scope of the class.
3. The function must be invoked upon an instance of the class (has a 'this' pointer).
A static member function declares the first two while a friend only declares the first. It therefore follows that if you believe a friend undermines encapsulation, then you must also believe every member function also undermines encapsulation -- and to a much greater degree. But you are the author of your own class' encapsulation rules; it's entirely up to you how you implement them, whether those implementations are within your own class member functions, your own static member functions or your own friends of the class.
Although friends are not physically members of your class, it would not be entirely wrong to think of them just as if they were. A friend declaration is itself a declaration so there's absolutely nothing to prevent you from defining it inline:
class year
{
// ...
friend std::ostream& operator<< (std::ostream& os, const year& y)
{
return os << y.m_data;
}
};
However, to keep your interface declaration "clean", it is best to place the implementation details outside the declaration, preferably alongside the other class member implementations.
Compound operators such as the increment-assign operator (+=) are often implemented as member functions, however there's no practical reason to do so, especially if you want to take advantage of implicit conversion. Use free functions wherever possible:
year& operator+= (year& lhs, const year& rhs)
{
lhs.m_data += rhs.m_data;
if (!lhs.m_data) throw std::range_error ("Error: no year zero!");
return lhs;
}
The above function must be declared a friend since it requires private access to the representation. However, note that you now have two places where you must check the invariant. Rather than duplicating the code, it would make sense to place that code in a private member function:
class year
{
// ...
private:
void check_invariants { if (!m_data) throw std::range_error ("Error: no year zero!"); }
};
Now the conversion constructor and increment assign operator can be simplified by calling this common method:
year::year (int64_t y): m_data {y} { check_invariants(); }
year& operator+= (year& lhs, const year& rhs)
{
lhs.m_data += rhs.m_data;
check_invariants();
return lhs;
}
With that done, all other increment operators can now be expressed in terms of this one overload without requiring friendship themselves:
// addition
year& operator+ (const year& lhs, const year& rhs)
{
return year {lhs} += rhs;
}
// prefix increment
year& operator++ (year& lhs)
{
return lhs += 1;
}
// postfix increment
year operator++ (year& lhs, const int)
{
year temp {lhs};
lhs += 1;
return temp;
}
All other operators can be implemented by the same means.
Remember, with the exception of the copy and move assignment operators, all other operator overloads should be implemented as free functions, with friend access only where required. Operators that are variations of each other (such as the increment operators), should be implemented in terms of one of those operators.
In some cases it can be helpful to provide a named member function in addition to or in place of an operator overload. For instance, the std::string& std::string::append (const std::string&) member function is synonymous with the std::string& operator+= (std:string&, const std::string&) operator overload. The first is implemented as a named member function, the second as a free function, where the free function simply invokes the member function. In cases where an operation might not be regarded as intuitive, a named member function is usually the best choice because the name can better express the notion of the operator than an operator alone can.
What is the program language c?
C is a pop language.
C is a case sensetive language.
C is motherof all language.
C is block structure language.
C is a high level language.
C is advace of B language.
C developed by D.richties in 1972 at AT & T Bell lab in USA.
Sachin Bhardwaj
986854722
skbmca@gmail.com
Which is 100 percent object oriented language?
There are relatively few 100% object-oriented programming languages, with C#, Ruby and SmallTalk being notable exceptions. Languages such as Java are not 100% object-oriented purely because they still maintain the concept of primitive data types, such as int and char, which are simply not capable of being treated as true objects.
Can you use friend functions to overload operators?
Yes you can. Although you will often hear it said that friend functions undermine encapsulation, this is errant nonsense. Here's a typical example:
#include <iostream>
using namespace std;
class Date
{
private:
int mo, da, yr;
public:
Date( int m, int d, int y ): mo(m), da(d), yr(y) {}
friend ostream& operator<<(ostream& os, const Date& dt);
};
ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
int main()
{
Date dt( 5, 6, 92 );
cout << dt;
return( 0 );
}
While it is possible to eliminate the friend function declaration simply by providing public accessors to Date::mo, Date::da and Date::yr, there is no advantage in doing so. You can still provide those accessors, of course, but since you'd need to return those members by value in order to maintain encapsulation, the operator overload would be less efficient as a result. In this case the difference is minimal but, with more complex members, the inefficiency can quickly add up.
Remember that friend functions merely extend the class interface. While it is true that you should not grant friend access to code that you have no control over (and thus undermine any concept of encapsulation), operator overloads such as the insertion operator overload shown above is under your complete control. Ultimately, if it were possible to declare the function as an actual member of the class then you would rightly do so. But that's precisely what you do when you declare friendship. And in this case, that friendship is perfectly legitimate because the alternative, non-friend function, would be less efficient.
What do you mean by operator precedence in c plus plus?
Operator overloading is a mechanism where a C++ developer can assign a special meaning to an operator (such as + or -, for example). This is useful, because it allows developers to create classes that can interact with other classes or primitives naturally, using the same syntax as you'd expect when working with primitives. For example, using operator overloading allows cin and cout to work "magically":
cout << "Hello World" << endl;
Even though it appears that these are just "shift operations", they take on the special meaning of outputting (for cout) and inputting (for cin) without resorting to a more cumbersome:
cout.print("Hello World\n");
This short example doesn't illustrate the savings that this syntax allows; a string of 20 variables would very nicely outline how the shift operators streamline cout.
Unfortunately, this usage is considered controversial, because it allows developers to use odd syntax. Consider the following:
Vehicle car = new Vehicle();
Velocity speed = new Velocity(15);
car += speed;
This is legal syntax with operator overloading. While it might make sense to some developers, others less familiar with a library might need to dig down into the code to make sure that the effect is what the developer intended. This can slow down development and debugging. It is this controversial usage that has prompted future languages, such as Java, to specifically exclude such functionality in an attempt to keep code as legible as possible.
How do you write a class in c plus plus?
Classes are not created, they are designed. A class is merely the definition of a type. The objects you instantiate from those classes are what are actually created, via the class constructors.
What is hierarchical inheritence in c plus plus?
Inheritance is used to define a subclass of a common ancestor. In other words, if you have a class that performs a set of functions, then a class that uses inheritance would have all the functions of the parent class plus additional or modified functions unique to that specific subclass. This allows developers to group common functionality into one class, then provide overrides and additional functionality to child classes. This facilitates code reuse, reduction of code duplication, and polymorphic functions that can operate on several different types of objects using the same base code.
Write a program in'C' language for the implementation of a Stack?
c program for implement a stack using two queue First push the given elements in stack1... then pop those elements and push them in 2nd stack... now pop the elements from this stack... thus implemented queue
If you are calling by reference it means that compilator will not create a local copy of the variable which you are referencing to. It will get access to the memory where the variable saved. When you are doing any operations with a referenced variable you can change the value of the variable.
It is a technique whereby the called function receives values from its calling function, stores these values in its local arguments and returns a result. The called function does not have access to any local variables in the calling function. Anything passed into the function call is unchanged in the caller's scope when the function returns.
No, C uses call-by-value. Of course you may use pointers as parameters.